|
| 1 | +import java.io.BufferedReader; |
| 2 | +import java.io.IOException; |
| 3 | +import java.io.InputStreamReader; |
| 4 | +import java.util.ArrayDeque; |
| 5 | +import java.util.Queue; |
| 6 | +import java.util.StringTokenizer; |
| 7 | + |
| 8 | +/** |
| 9 | + * 백준 1600번 말이 되고픈 원숭이 |
| 10 | + * - BFS? |
| 11 | + */ |
| 12 | + |
| 13 | +public class Main { |
| 14 | + public static int[][] horse = {{-2, -1}, {2, 1}, {-1, -2}, {1, 2}, {-2, 1}, {2, -1}, {1, -2}, {-1, 2}}; |
| 15 | + public static int[][] kiki = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + int K = Integer.parseInt(br.readLine()); |
| 20 | + |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + int W = Integer.parseInt(st.nextToken()); |
| 23 | + int H = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + int[][] map = new int[H][W]; |
| 26 | + |
| 27 | + for (int i = 0; i < H; i++) { |
| 28 | + st = new StringTokenizer(br.readLine()); |
| 29 | + for (int j = 0; j < W; j++) { |
| 30 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + int answer = -1; |
| 35 | + |
| 36 | + Queue<int[]> queue = new ArrayDeque<>(); |
| 37 | + boolean[][][] visited = new boolean[H][W][K + 1]; |
| 38 | + |
| 39 | + // {x 좌표, y 좌표, 말 이동 횟수, 이동 횟수} |
| 40 | + queue.offer(new int[] {0, 0, 0, 0}); |
| 41 | + visited[0][0][0] = true; |
| 42 | + |
| 43 | + while (!queue.isEmpty()) { |
| 44 | + int[] cur = queue.poll(); |
| 45 | + |
| 46 | + int x = cur[0]; |
| 47 | + int y = cur[1]; |
| 48 | + int horseCnt = cur[2]; |
| 49 | + int dist = cur[3]; |
| 50 | + |
| 51 | + if (x == H - 1 && y == W - 1) { |
| 52 | + answer = dist; |
| 53 | + break; |
| 54 | + } |
| 55 | + |
| 56 | + for (int i = 0; i < 4; i++) { |
| 57 | + int dx = x + kiki[i][0]; |
| 58 | + int dy = y + kiki[i][1]; |
| 59 | + |
| 60 | + if (dx < 0 || dy < 0 || dx >= H || dy >= W || map[dx][dy] == 1) continue; |
| 61 | + |
| 62 | + if (!visited[dx][dy][horseCnt]) { |
| 63 | + queue.offer(new int[] {dx, dy, horseCnt, dist + 1}); |
| 64 | + visited[dx][dy][horseCnt] = true; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + if (horseCnt < K) { |
| 69 | + for (int i = 0; i < 8; i++) { |
| 70 | + int dx = x + horse[i][0]; |
| 71 | + int dy = y + horse[i][1]; |
| 72 | + |
| 73 | + if (dx < 0 || dy < 0 || dx >= H || dy >= W || map[dx][dy] == 1) continue; |
| 74 | + |
| 75 | + if (!visited[dx][dy][horseCnt + 1]) { |
| 76 | + queue.offer(new int[] {dx, dy, horseCnt + 1, dist + 1}); |
| 77 | + visited[dx][dy][horseCnt + 1] = true; |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + System.out.println(answer); |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments