|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static int n, m, k; |
| 8 | + static int[][] map; |
| 9 | + static boolean[][][] visited; |
| 10 | + static int[] dr = {-1, 1, 0, 0}; |
| 11 | + static int[] dc = {0, 0, -1, 1}; |
| 12 | + |
| 13 | + static class dot { |
| 14 | + int r, c, b; |
| 15 | + |
| 16 | + public dot(int r, int c, int b) { |
| 17 | + this.r = r; |
| 18 | + this.c = c; |
| 19 | + this.b = b; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public static void main(String[] args) throws Exception { |
| 24 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 25 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 26 | + |
| 27 | + n = Integer.parseInt(st.nextToken()); |
| 28 | + m = Integer.parseInt(st.nextToken()); |
| 29 | + k = Integer.parseInt(st.nextToken()); |
| 30 | + |
| 31 | + map = new int[n][m]; |
| 32 | + visited = new boolean[n][m][k + 1]; |
| 33 | + |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + String s = br.readLine(); |
| 36 | + for (int j = 0; j < m; j++) { |
| 37 | + map[i][j] = Integer.parseInt(String.valueOf(s.charAt(j))); |
| 38 | + } |
| 39 | + } |
| 40 | + if(n==1&&m==1){ |
| 41 | + System.out.println(1); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + bfs(); |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + static void bfs() { |
| 50 | + Queue<dot> list = new ArrayDeque<>(); |
| 51 | + list.add(new dot(0, 0, 0)); |
| 52 | + visited[0][0][0] = true; |
| 53 | + int cnt = 1; |
| 54 | + |
| 55 | + while (!list.isEmpty()) { |
| 56 | + int s = list.size(); |
| 57 | + for (int i = 0; i < s; i++) { |
| 58 | + dot cur = list.poll(); |
| 59 | + int row = cur.r; |
| 60 | + int col = cur.c; |
| 61 | + int brk = cur.b; |
| 62 | + |
| 63 | + for (int d = 0; d < 4; d++) { |
| 64 | + int nr = row + dr[d]; |
| 65 | + int nc = col + dc[d]; |
| 66 | + if (nr < 0 || nr >= n || nc < 0 || nc >= m || visited[nr][nc][brk] || map[nr][nc] == 1) |
| 67 | + continue; |
| 68 | + visited[nr][nc][brk] = true; |
| 69 | + list.add(new dot(nr, nc, brk)); |
| 70 | + if (nr == n - 1 && nc == m - 1) { |
| 71 | + System.out.println(cnt + 1); |
| 72 | + return; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if (brk < k) { |
| 77 | + for (int d = 0; d < 4; d++) { |
| 78 | + int nr = row + dr[d]; |
| 79 | + int nc = col + dc[d]; |
| 80 | + int nb = brk + 1; |
| 81 | + if (nr < 0 || nr >= n || nc < 0 || nc >= m) continue; |
| 82 | + if (map[nr][nc] != 1) continue; |
| 83 | + if (visited[nr][nc][nb]) continue; |
| 84 | + visited[nr][nc][nb] = true; |
| 85 | + list.add(new dot(nr, nc, nb)); |
| 86 | + if (nr == n - 1 && nc == m - 1) { |
| 87 | + System.out.println(cnt + 1); |
| 88 | + return; |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + cnt++; |
| 94 | + } |
| 95 | + System.out.println(-1); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +``` |
0 commit comments