|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static Position king; |
| 7 | + public static void main(String[] args) throws Exception { |
| 8 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 9 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 10 | + |
| 11 | + int[][] dir = new int[][] {{-3,-2},{-3,2},{3,-2},{3,2},{2,-3},{-2,-3},{-2,3},{2,3}}; |
| 12 | + Position sang; |
| 13 | + boolean[][] visited = new boolean[10][9]; |
| 14 | + |
| 15 | + sang = new Position(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0); |
| 16 | + st = new StringTokenizer(br.readLine()); |
| 17 | + king = new Position(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), 0); |
| 18 | + |
| 19 | + Queue<Position> q = new LinkedList<>(); |
| 20 | + q.add(sang); |
| 21 | + visited[sang.y][sang.x] = true; |
| 22 | + while(!q.isEmpty()) { |
| 23 | + Position curr = q.poll(); |
| 24 | + for (int[] d : dir) { |
| 25 | + int ny = curr.y + d[0]; |
| 26 | + int nx = curr.x + d[1]; |
| 27 | + if (ny >= 10 || ny < 0 || nx >= 9 || nx < 0 || visited[ny][nx]) continue; |
| 28 | + if (check(d, curr)) continue; |
| 29 | + if (ny == king.y && nx == king.x) { |
| 30 | + System.out.println(curr.m+1); |
| 31 | + return; |
| 32 | + } |
| 33 | + q.add(new Position(ny, nx, curr.m+1)); |
| 34 | + visited[ny][nx] = true; |
| 35 | + } |
| 36 | + } |
| 37 | + System.out.println(-1); |
| 38 | + } |
| 39 | + static boolean check(int[] d, Position curr) { |
| 40 | + if (Math.abs(d[0]) == 2) { |
| 41 | + int ny = curr.y; |
| 42 | + int nx = curr.x + d[1]/3; |
| 43 | + if(ny == king.y && nx == king.x) return true; |
| 44 | + ny += d[0]/2; |
| 45 | + nx += d[1]/3; |
| 46 | + if(ny == king.y && nx == king.x) return true; |
| 47 | + } else { |
| 48 | + int ny = curr.y + d[0]/3; |
| 49 | + int nx = curr.x; |
| 50 | + if(ny == king.y && nx == king.x) return true; |
| 51 | + ny += d[0]/3; |
| 52 | + nx += d[1]/2; |
| 53 | + if(ny == king.y && nx == king.x) return true; |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + static class Position { |
| 59 | + int y; |
| 60 | + int x; |
| 61 | + int m; |
| 62 | + public Position(int y, int x, int m) { |
| 63 | + this.y = y; |
| 64 | + this.x = x; |
| 65 | + this.m = m; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments