|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N, M, K; |
| 7 | + static int[][] map; |
| 8 | + static boolean[][][] visited; |
| 9 | + static int[] dx = {-1, 1, 0, 0}; |
| 10 | + static int[] dy = {0, 0, -1, 1}; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 15 | + |
| 16 | + N = Integer.parseInt(st.nextToken()); |
| 17 | + M = Integer.parseInt(st.nextToken()); |
| 18 | + K = Integer.parseInt(st.nextToken()); |
| 19 | + |
| 20 | + map = new int[N][M]; |
| 21 | + visited = new boolean[N][M][K + 1]; |
| 22 | + |
| 23 | + for (int i = 0; i < N; i++) { |
| 24 | + String line = br.readLine(); |
| 25 | + for (int j = 0; j < M; j++) { |
| 26 | + map[i][j] = line.charAt(j) - '0'; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + System.out.println(bfs()); |
| 31 | + } |
| 32 | + |
| 33 | + static int bfs() { |
| 34 | + ArrayDeque<Node> queue = new ArrayDeque<>(); |
| 35 | + queue.offer(new Node(0, 0, 0, 1)); |
| 36 | + visited[0][0][0] = true; |
| 37 | + |
| 38 | + while (!queue.isEmpty()) { |
| 39 | + Node current = queue.poll(); |
| 40 | + |
| 41 | + if (current.x == N - 1 && current.y == M - 1) { |
| 42 | + return current.dist; |
| 43 | + } |
| 44 | + |
| 45 | + for (int i = 0; i < 4; i++) { |
| 46 | + int nx = current.x + dx[i]; |
| 47 | + int ny = current.y + dy[i]; |
| 48 | + |
| 49 | + if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue; |
| 50 | + |
| 51 | + if (map[nx][ny] == 0 && !visited[nx][ny][current.broken]) { |
| 52 | + visited[nx][ny][current.broken] = true; |
| 53 | + queue.offer(new Node(nx, ny, current.broken, current.dist + 1)); |
| 54 | + } else if (map[nx][ny] == 1 && current.broken < K && !visited[nx][ny][current.broken + 1]) { |
| 55 | + visited[nx][ny][current.broken + 1] = true; |
| 56 | + queue.offer(new Node(nx, ny, current.broken + 1, current.dist + 1)); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return -1; |
| 62 | + } |
| 63 | + |
| 64 | + static class Node { |
| 65 | + int x, y, broken, dist; |
| 66 | + |
| 67 | + Node(int x, int y, int broken, int dist) { |
| 68 | + this.x = x; |
| 69 | + this.y = y; |
| 70 | + this.broken = broken; |
| 71 | + this.dist = dist; |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
0 commit comments