|
| 1 | +import java.io.BufferedReader; |
| 2 | +//import java.io.FileInputStream; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + private static int[][] map; |
| 9 | + private static int[] dx = {1, 0, -1, 0}; |
| 10 | + private static int[] dy = {0, 1, 0, -1}; |
| 11 | + |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + //System.setIn(new FileInputStream("input.txt")); // 제출 시 이 줄만 주석처리 |
| 14 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 16 | + |
| 17 | + int n = Integer.parseInt(st.nextToken()); |
| 18 | + int m = Integer.parseInt(st.nextToken()); |
| 19 | + |
| 20 | + map = new int[n][m]; |
| 21 | + for (int i = 0; i < n; i++) { |
| 22 | + String line = br.readLine(); |
| 23 | + for (int j = 0; j < line.length(); j++) { |
| 24 | + map[i][j] = Integer.parseInt(String.valueOf(line.charAt(j))); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + Deque<int[]> deque = new ArrayDeque<>(); |
| 29 | + boolean[][] visited = new boolean[n][m]; |
| 30 | + deque.add(new int[]{0, 0, 1}); |
| 31 | + visited[0][0] = true; |
| 32 | + |
| 33 | + while (!deque.isEmpty()) { |
| 34 | + int[] cur = deque.poll(); |
| 35 | + int cx = cur[0]; |
| 36 | + int cy = cur[1]; |
| 37 | + int dist = cur[2]; |
| 38 | + if (cx == n - 1 && cy == m - 1) { |
| 39 | + System.out.println(dist); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + for (int i = 0; i < 4; i++) { |
| 44 | + int nx = cx + dx[i]; |
| 45 | + int ny = cy + dy[i]; |
| 46 | + |
| 47 | + if (nx >= 0 && nx < n && ny >= 0 && ny < m && !visited[nx][ny] && map[nx][ny] == 1) { |
| 48 | + visited[nx][ny] = true; |
| 49 | + deque.add(new int[]{nx, ny, dist + 1}); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments