|
| 1 | +```java |
| 2 | +package etc; |
| 3 | + |
| 4 | +import java.io.*; |
| 5 | +import java.util.ArrayDeque; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Deque; |
| 8 | + |
| 9 | +public class BJ_2665_미로만들기 { |
| 10 | + |
| 11 | + private static final int[] dx = { 0, 0, -1, 1 }; |
| 12 | + private static final int[] dy = { -1, 1, 0, 0 }; |
| 13 | + |
| 14 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 15 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 16 | + |
| 17 | + private static int N; |
| 18 | + private static int[][] dist; |
| 19 | + private static char[][] matrix; |
| 20 | + private static Deque<Node> dq; |
| 21 | + |
| 22 | + private static class Node { |
| 23 | + int x; |
| 24 | + int y; |
| 25 | + int cnt; |
| 26 | + |
| 27 | + Node(int x, int y, int cnt) { |
| 28 | + this.x = x; |
| 29 | + this.y = y; |
| 30 | + this.cnt = cnt; |
| 31 | + } |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + public static void main(String[] args) throws IOException { |
| 36 | + init(); |
| 37 | + sol(); |
| 38 | + } |
| 39 | + |
| 40 | + private static void init() throws IOException { |
| 41 | + N = Integer.parseInt(br.readLine()); |
| 42 | + |
| 43 | + matrix = new char[N][N]; |
| 44 | + for (int i = 0; i < N; i++) { |
| 45 | + String s = br.readLine(); |
| 46 | + for (int j = 0; j < N; j++) { |
| 47 | + matrix[i][j] = s.charAt(j); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + dist = new int[N][N]; |
| 52 | + for (int[] row : dist) { |
| 53 | + Arrays.fill(row, Integer.MAX_VALUE); |
| 54 | + } |
| 55 | + |
| 56 | + dq = new ArrayDeque<>(); |
| 57 | + } |
| 58 | + |
| 59 | + private static void sol() throws IOException { |
| 60 | + dq.offer(new Node(0, 0, 0)); |
| 61 | + dist[0][0] = 0; |
| 62 | + |
| 63 | + while (!dq.isEmpty()) { |
| 64 | + Node cur = dq.poll(); |
| 65 | + |
| 66 | + if (cur.x == N - 1 && cur.y == N - 1) { |
| 67 | + bw.write(cur.cnt + ""); |
| 68 | + bw.flush(); |
| 69 | + bw.close(); |
| 70 | + br.close(); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + if (cur.cnt > dist[cur.x][cur.y]) continue; |
| 75 | + |
| 76 | + for (int d = 0; d < 4; d++) { |
| 77 | + int nx = cur.x + dx[d]; |
| 78 | + int ny = cur.y + dy[d]; |
| 79 | + |
| 80 | + if (OOB(nx, ny)) continue; |
| 81 | + |
| 82 | + int newCost = cur.cnt + (matrix[nx][ny] == '0' ? 1 : 0); |
| 83 | + |
| 84 | + if (newCost < dist[nx][ny]) { |
| 85 | + dist[nx][ny] = newCost; |
| 86 | + |
| 87 | + if (matrix[nx][ny] == '1') { |
| 88 | + dq.offerFirst(new Node(nx, ny, newCost)); |
| 89 | + } else { |
| 90 | + dq.offerLast(new Node(nx, ny, newCost)); |
| 91 | + } |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + private static boolean OOB(int x, int y) { |
| 98 | + return x < 0 || N <= x || y < 0 || N <= y; |
| 99 | + } |
| 100 | + |
| 101 | +} |
| 102 | +``` |
0 commit comments