01-08 08:57
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_64 ๋ฏธ๋กœ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ†ต๋กœ (BFS) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_64 ๋ฏธ๋กœ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ†ต๋กœ (BFS)

miinsun 2022. 3. 3. 19:30

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

7*7 ๊ฒฉ์žํŒ ๋ฏธ๋กœ๋ฅผ ํƒˆ์ถœํ•˜๋Š” ์ตœ๋‹จ๊ฒฝ๋กœ์˜ ๊ธธ์ด๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

๊ฒฝ๋กœ์˜ ๊ธธ์ด๋Š” ์ถœ๋ฐœ์ ์—์„œ ๋„์ฐฉ์ ๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ ์ด๋™ํ•œ ํšŸ์ˆ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค.
์ถœ๋ฐœ์ ์€ ๊ฒฉ์ž์˜ (0, 0) ์ขŒํ‘œ์ด๊ณ , ํƒˆ์ถœ ๋„์ฐฉ์ ์€ (6, 6)์ขŒํ‘œ์ด๋‹ค. ๊ฒฉ์žํŒ์˜ 1์€ ๋ฒฝ์ด๊ณ , 0์€ ๋„๋กœ์ด๋‹ค.

๊ฒฉ์žํŒ์˜ ์›€์ง์ž„์€ ์ƒํ•˜์ขŒ์šฐ๋กœ๋งŒ ์›€์ง์ธ๋‹ค.

๋ฏธ๋กœ๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์€ ๊ฒฝ๋กœ๋กœ ์ตœ๋‹จ ๊ฒฝ๋กœ์˜ ๊ธธ์ด๋Š” 12์ด๋‹ค.

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ 7*7 ๊ฒฉ์ž์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

0 0 0 0 0 0 0
0 1 1 1 1 1 0
0 0 0 1 0 0 0
1 1 0 1 0 1 1
1 1 0 1 0 0 0
1 0 0 0 1 0 0
1 0 1 0 0 0 0

์ถœ๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ตœ๋‹จ์œผ๋กœ ์›€์ง์ธ ์นธ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋„์ฐฉํ•  ์ˆ˜ ์—†์œผ๋ฉด -1๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

12

 

๐Ÿ’ป Solution.java

import java.util.*;

class Point {
	public int x, y;
	Point (int x, int y){
		this.x = x;
		this.y = y;
	}
}

public class Main {
	static int[][] board, dis;
	static int[] dx = {-1, 0, 1, 0};
	static int[] dy = {0, 1, 0, -1};
		
	public void BFS(int x, int y) {
		Queue<Point> Q = new LinkedList<>();
		Q.offer(new Point(x, y));
		board[x][y] = 1;
		
		while(!Q.isEmpty()) {
			Point tmp = Q.poll();
			for(int i = 0; i < 4; i++) {
				int nx = tmp.x + dx[i];
				int ny = tmp.y + dy[i];
				
				// ๊ฒฝ๊ณ„์„  ๊ฒ€์‚ฌ
				if(nx >= 0 && nx <=6 && ny >= 0 && ny <= 6 && board[nx][ny] == 0) {
					board[nx][ny] = 1;
					Q.offer(new Point(nx, ny));
					dis[nx][ny] = dis[tmp.x][tmp.y] + 1;
				}
			}
		}
 	}
	
	public static void main(String[] args){
		Main main = new Main();
		Scanner sc = new Scanner(System.in);

		board = new int[7][7];
		dis = new int[7][7];
		
		for(int i = 0; i < 7; i++) {
			for(int j = 0; j < 7; j++) {
				board[i][j] = sc.nextInt();
			}
		}
	
		main.BFS(0, 0);
		if(dis[6][6] == 0) System.out.println(-1);
		else System.out.println(dis[6][6]);
		
		sc.close();
		return ;
	}
}

 

Comments