|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 6 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 7 | + static StringTokenizer st; |
| 8 | + static int[][] distance; |
| 9 | + static int N; |
| 10 | + static int M; |
| 11 | + static int[][] maze; |
| 12 | + static int[] dx = { 0, 0, 1, -1 }; |
| 13 | + static int[] dy = { 1, -1, 0, 0 }; |
| 14 | + |
| 15 | + public static void main(String[] args) throws IOException { |
| 16 | + st = new StringTokenizer(br.readLine()); |
| 17 | + N = Integer.valueOf(st.nextToken()); |
| 18 | + M = Integer.valueOf(st.nextToken()); |
| 19 | + maze = new int[N][M]; |
| 20 | + distance = new int[N][M]; |
| 21 | + |
| 22 | + for (int i = 0; i < N; i++) { |
| 23 | + String line = br.readLine(); |
| 24 | + for (int j = 0; j < M; j++) { |
| 25 | + maze[i][j] = line.charAt(j) - '0'; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + bfs(0, 0); |
| 30 | + bw.write(String.valueOf(distance[N - 1][M - 1])); |
| 31 | + bw.close(); |
| 32 | + } |
| 33 | + |
| 34 | + public static void bfs(int x, int y) { |
| 35 | + Deque<int[]> queue = new ArrayDeque<>(); |
| 36 | + queue.add(new int[] { x, y }); |
| 37 | + distance[x][y] = 1; |
| 38 | + |
| 39 | + while (!queue.isEmpty()) { |
| 40 | + int current_x = queue.getFirst()[0]; |
| 41 | + int current_y = queue.getFirst()[1]; |
| 42 | + queue.poll(); |
| 43 | + |
| 44 | + for (int i = 0; i < 4; i++) { |
| 45 | + int next_x = current_x + dx[i]; |
| 46 | + int next_y = current_y + dy[i]; |
| 47 | + |
| 48 | + if (next_x < 0 || next_y < 0 || next_x >= N || next_y >= M) { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + if (maze[next_x][next_y] == 0 || distance[next_x][next_y] != 0) { |
| 53 | + continue; |
| 54 | + } |
| 55 | + |
| 56 | + queue.add(new int[] { next_x, next_y }); |
| 57 | + distance[next_x][next_y] = distance[current_x][current_y] + 1; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments