N×M크기의 배열로 표현되는 미로가 있다.
1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1
미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.
위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
그래프 탐색 문제 -> BFS DFS 중 하나로 해결 가능,
현재 문제를 봤을 때는 BFS로 푸는 편이 바르다고 생각됨
public class Main {
static int[][] map;
static int n;
static int m;
static int[][] visit;
static int[][] count;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
map = new int[n][m];
visit = new int[n][m];
count = new int[n][m];
for (int i = 0; i < n; i++) {
String s = scanner.next();
for (int j = 0; j < m; j++) {
map[i][j] = (int) s.charAt(j) - '0';
}
}
map[0][0] = 1;
visit[0][0] = 1;
count[0][0] = 1;
BFS();
System.out.println(count[n-1][m-1]);
}
public static void BFS(){
int x;
int y;
Queue<Integer> queue = new ArrayDeque<>(n*m);
queue.add(0);
queue.add(0);
while(!queue.isEmpty()){
x = queue.poll();
y = queue.poll();
//위
if (x > 0){
if (map[x-1][y] == 1 && visit[x-1][y] == 0){
count[x - 1][y] = count[x][y] + 1;
queue.add(x-1);
queue.add(y);
visit[x - 1][y] = 1;
}
}
//아래
if (x < n-1) {
if (map[x+1][y] == 1 && visit[x+1][y] == 0){
count[x + 1][y] = count[x][y] + 1;
queue.add(x+1);
queue.add(y);
visit[x + 1][y] = 1;
}
}
//왼쪽
if (y > 0){
if (map[x][y-1] == 1 && visit[x][y-1] == 0) {
count[x][y - 1] = count[x][y] + 1;
queue.add(x);
queue.add(y - 1);
visit[x][y - 1] = 1;
}
}
//오른쪽
if (y < m-1) {
if (map[x][y+1] == 1 && visit[x][y+1] == 0) {
count[x][y + 1] = count[x][y] + 1;
queue.add(x);
queue.add(y + 1);
visit[x][y + 1] = 1;
}
}
}
}
}