|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int n; |
| 7 | + static int[][] map; |
| 8 | + static int[][] dist; |
| 9 | + static int[] dx = {1, -1, 0, 0}; |
| 10 | + static int[] dy = {0, 0, 1, -1}; |
| 11 | + static final int INF = 987654321; |
| 12 | + |
| 13 | + static class Node { |
| 14 | + int x, y; |
| 15 | + Node(int x, int y) { |
| 16 | + this.x = x; |
| 17 | + this.y = y; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public static void main(String[] args) throws IOException { |
| 22 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 23 | + n = Integer.parseInt(br.readLine()); |
| 24 | + map = new int[n][n]; |
| 25 | + dist = new int[n][n]; |
| 26 | + |
| 27 | + for (int i = 0; i < n; i++) { |
| 28 | + String line = br.readLine(); |
| 29 | + for (int j = 0; j < n; j++) { |
| 30 | + map[i][j] = line.charAt(j) - '0'; |
| 31 | + dist[i][j] = INF; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + bfs(); |
| 36 | + System.out.println(dist[n - 1][n - 1]); |
| 37 | + } |
| 38 | + |
| 39 | + static void bfs() { |
| 40 | + Deque<Node> dq = new ArrayDeque<>(); |
| 41 | + dist[0][0] = 0; |
| 42 | + dq.add(new Node(0, 0)); |
| 43 | + |
| 44 | + while (!dq.isEmpty()) { |
| 45 | + Node cur = dq.pollFirst(); |
| 46 | + int x = cur.x, y = cur.y; |
| 47 | + |
| 48 | + for (int dir = 0; dir < 4; dir++) { |
| 49 | + int nx = x + dx[dir]; |
| 50 | + int ny = y + dy[dir]; |
| 51 | + if (nx < 0 || ny < 0 || nx >= n || ny >= n) continue; |
| 52 | + |
| 53 | + int cost = (map[nx][ny] == 0 ? 1 : 0); |
| 54 | + if (dist[x][y] + cost < dist[nx][ny]) { |
| 55 | + dist[nx][ny] = dist[x][y] + cost; |
| 56 | + if (cost == 0) dq.addFirst(new Node(nx, ny)); |
| 57 | + else dq.addLast(new Node(nx, ny)); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +``` |
0 commit comments