|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class boj1600 { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static StringTokenizer st; |
| 8 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 9 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 10 | + |
| 11 | + static int[][] dir = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; |
| 12 | + static int[][] hdir = new int[][] {{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}}; |
| 13 | + static int K, W, H; |
| 14 | + static int[][] board; |
| 15 | + static boolean[][][] visited; |
| 16 | + public static void main(String[] args) throws Exception { |
| 17 | + nextLine(); |
| 18 | + K = nextInt(); |
| 19 | + nextLine(); |
| 20 | + W = nextInt(); |
| 21 | + H = nextInt(); |
| 22 | + board = new int[H][W]; |
| 23 | + visited = new boolean[H][W][K+1]; |
| 24 | + for (int i = 0; i < H; i++) { |
| 25 | + nextLine(); |
| 26 | + for (int j = 0; j < W; j++) { |
| 27 | + board[i][j] = nextInt(); |
| 28 | + } |
| 29 | + } |
| 30 | + bfs(); |
| 31 | + } |
| 32 | + |
| 33 | + static void bfs() { |
| 34 | + Queue<Move> q = new LinkedList<>(); |
| 35 | + q.add(new Move(0, 0, 0, 0)); |
| 36 | + visited[0][0][0] = true; |
| 37 | + |
| 38 | + while (!q.isEmpty()) { |
| 39 | + Move cur = q.poll(); |
| 40 | + if (cur.y == H-1 && cur.x == W-1) { |
| 41 | + System.out.println(cur.dep); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + for (int[] d : dir) { |
| 46 | + int ny = cur.y + d[0]; |
| 47 | + int nx = cur.x + d[1]; |
| 48 | + if (ny >= H || ny < 0 || nx >= W || nx < 0 || board[ny][nx] == 1) continue; |
| 49 | + |
| 50 | + if (!visited[ny][nx][cur.horse]) { |
| 51 | + visited[ny][nx][cur.horse] = true; |
| 52 | + q.offer(new Move(ny, nx, cur.horse, cur.dep + 1)); |
| 53 | + } |
| 54 | + } |
| 55 | + if (cur.horse < K) { |
| 56 | + for (int[] d : hdir) { |
| 57 | + int ny = cur.y + d[0]; |
| 58 | + int nx = cur.x + d[1]; |
| 59 | + if (ny >= H || ny < 0 || nx >= W || nx < 0 || board[ny][nx] == 1) continue; |
| 60 | + if (!visited[ny][nx][cur.horse+1]) { |
| 61 | + visited[ny][nx][cur.horse+1] = true; |
| 62 | + q.offer(new Move(ny, nx, cur.horse+1, cur.dep + 1)); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + System.out.println(-1); |
| 68 | + } |
| 69 | + |
| 70 | + static class Move { |
| 71 | + int y, x, horse, dep; |
| 72 | + public Move(int y, int x, int horse, int dep) { |
| 73 | + this.y = y; |
| 74 | + this.x = x; |
| 75 | + this.horse = horse; |
| 76 | + this.dep = dep; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
0 commit comments