|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + private static int[][] d = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}}; |
| 6 | + private static int l; |
| 7 | + |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + |
| 11 | + int t = Integer.parseInt(br.readLine()); |
| 12 | + |
| 13 | + StringBuilder sb = new StringBuilder(); |
| 14 | + for(int test=0; test<t; test++) { |
| 15 | + l = Integer.parseInt(br.readLine()); |
| 16 | + |
| 17 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 18 | + int[] start = new int[] {Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; |
| 19 | + |
| 20 | + st = new StringTokenizer(br.readLine()); |
| 21 | + int[] end = new int[] {Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; |
| 22 | + |
| 23 | + int result = bfs(start, end); |
| 24 | + |
| 25 | + sb.append(result).append("\n"); |
| 26 | + } |
| 27 | + |
| 28 | + System.out.println(sb.toString().trim()); |
| 29 | + } |
| 30 | + |
| 31 | + private static int bfs(int[] start, int[] end) { |
| 32 | + Queue<int[]> queue = new LinkedList<>(); |
| 33 | + boolean[][] visited = new boolean[l][l]; |
| 34 | + |
| 35 | + queue.offer(new int[] {start[0], start[1], 0}); |
| 36 | + visited[start[0]][start[1]] = true; |
| 37 | + |
| 38 | + while(!queue.isEmpty()) { |
| 39 | + int[] info = queue.poll(); |
| 40 | + int x = info[0]; |
| 41 | + int y = info[1]; |
| 42 | + int count = info[2]; |
| 43 | + |
| 44 | + if(x == end[0] && y == end[1]) return count; |
| 45 | + |
| 46 | + for(int i=0; i<d.length; i++) { |
| 47 | + int nx = x + d[i][0]; |
| 48 | + int ny = y + d[i][1]; |
| 49 | + if(nx<0 || nx>=l || ny<0 || ny>=l || visited[nx][ny]) continue; |
| 50 | + |
| 51 | + visited[nx][ny] = true; |
| 52 | + queue.offer(new int[] {nx, ny, count+1}); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return -1; |
| 57 | + } |
| 58 | +} |
0 commit comments