
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[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int[][] board, dis;
static int answer = 0;
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();
//꺼낸 다음 뻗어나가기
//while이 끝나면 dis배열은 꽉채워져 있다.
for(int i = 0; i < 4; i++) {
int nx = tmp.x + dx[i];
int ny = tmp.y + dy[i];
//경계선 및 통로 확인
if(nx >= 1 && nx <= 7 && ny >= 1 && ny <= 7 && 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 T = new Main();
Scanner kb = new Scanner(System.in);
board = new int[8][8];
dis = new int[8][8];
for(int i = 1; i <= 7; i++) {
for(int j = 1; j <= 7; j++) {
board[i][j] = kb.nextInt();
}
}
T.BFS(1, 1);
if(dis[7][7] == 0) System.out.println(-1);
else {
System.out.println(dis[7][7]);
}
}
}
q가 빌 때 까지 도는데 16이라는 값으로 덮어쓰기가 안되는 이유는
값이 한번 들어가면 해당 지점은 방문처리가 되어버리기 때문이다.!

'Algorithm > inflearn' 카테고리의 다른 글
| 섬나라 아일랜드(DFS) (0) | 2021.10.05 |
|---|---|
| 토마토(BFS 활용) (0) | 2021.10.05 |
| 미로탐색(DFS) (0) | 2021.10.05 |
| ★★★조합 구하기(DFS) (0) | 2021.10.04 |
| 조합수(메모이제이션) (0) | 2021.10.04 |