|
| 1 | +import java.util.*; |
| 2 | +import java.io.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + static int visited[][]; |
| 6 | + static int arr[][]; |
| 7 | + static int dx[] ={-1, -2, -2,-1, 1,2,2,1}; |
| 8 | + static int dy[] = {-2,-1,1,2,-2,-1,1,2}; |
| 9 | + static int I,startX,startY,endX,endY; |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + |
| 12 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + |
| 14 | + int T = Integer.parseInt(br.readLine()); |
| 15 | + StringTokenizer st; |
| 16 | + StringBuilder sb = new StringBuilder(); |
| 17 | + |
| 18 | + for(int i=0;i <T; i++) { |
| 19 | + I = Integer.parseInt(br.readLine()); |
| 20 | + arr = new int[I][I]; |
| 21 | + st = new StringTokenizer(br.readLine()); |
| 22 | + startX = Integer.parseInt(st.nextToken()); |
| 23 | + startY = Integer.parseInt(st.nextToken()); |
| 24 | + |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + endX = Integer.parseInt(st.nextToken()); |
| 27 | + endY = Integer.parseInt(st.nextToken()); |
| 28 | + visited = new int[I][I]; |
| 29 | + if(startX == endX && startY == endY) { |
| 30 | + sb.append(0).append("\n"); |
| 31 | + } |
| 32 | + else |
| 33 | + sb.append(bfs(startX,startY)).append("\n"); |
| 34 | + } |
| 35 | + System.out.println(sb); |
| 36 | + } |
| 37 | + |
| 38 | + static int bfs(int x, int y) { |
| 39 | + |
| 40 | + Queue<int[]> queue = new LinkedList<>(); |
| 41 | + |
| 42 | + queue.add(new int[] {x,y}); |
| 43 | + visited[x][y]=0; |
| 44 | + |
| 45 | + while(!queue.isEmpty()) { |
| 46 | + |
| 47 | + int size = queue.size(); |
| 48 | + |
| 49 | + int now[] = queue.poll(); |
| 50 | + int nowx = now[0]; |
| 51 | + int nowy = now[1]; |
| 52 | + |
| 53 | + for(int i=0; i< 8; i++) { |
| 54 | + int nx = nowx + dx[i]; |
| 55 | + int ny = nowy + dy[i]; |
| 56 | + if(nx >=0&& nx <I && ny >=0 && ny <I) { |
| 57 | + if(visited[nx][ny] ==0) { |
| 58 | + visited[nx][ny] = visited[nowx][nowy]+1; |
| 59 | + queue.add(new int[]{nx,ny}); |
| 60 | + if(nx == endX && ny == endY) { |
| 61 | + return visited[nx][ny]; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + } |
| 68 | + return -1; |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments