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)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
4 6
101111
101010
101011
111011
15
4 6
110110
110110
111111
111101
9
2 25
1011101110111011101110111
1110111011101110111011101
38
7 7
1011111
1110001
1000001
1000001
1000001
1000001
1111111
13
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
boolean[][] map = new boolean[n][m];
for (int i = 0; i < n; i++) {
char[] input = br.readLine().toCharArray();
for (int j = 0; j < m; j++) {
map[i][j] = input[j] == '1' ? true : false;
}
}
int[] mx = {0, 0, -1, 1};
int[] my = {-1, 1, 0, 0};
Queue<Pair> queue = new LinkedList<>();
queue.offer(new Pair(0, 0));
int[][] visited = new int[n][m];
visited[0][0] = 1;
while (!queue.isEmpty()){
Pair now = queue.poll();
if(now.x == n - 1 && now.y == m - 1)
break;
for(int i = 0; i < mx.length; i++){
int dx = now.x + mx[i];
int dy = now.y + my[i];
if((dx >= 0 && dx < n) && (dy >= 0 && dy < m)){
if(visited[dx][dy] == 0 && map[dx][dy]){
visited[dx][dy] = visited[now.x][now.y] + 1;
queue.offer(new Pair(dx, dy));
}
}
}
}
System.out.println(visited[n - 1][m - 1]);
}
static class Pair{
public int x;
public int y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
}
}