나이트의 이동(7562)
Last updated
Last updated
5
28
0import java.util.*;
import java.io.*;
public class Main{
static int size, startX, startY, endX, endY;
static int[][] arr;
static boolean[][] visited;
static int[] dx = {-1, 1, -1, 1, -2, -2, 2, 2};
static int[] dy = {2, 2, -2, -2, 1, -1, 1, -1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
for(int i=0; i<n; i++){
size = Integer.parseInt(br.readLine());
arr = new int[size][size];
visited = new boolean[size][size];
st = new StringTokenizer(br.readLine(), " ");
startX = Integer.parseInt(st.nextToken());
startY = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine(), " ");
endX = Integer.parseInt(st.nextToken());
endY = Integer.parseInt(st.nextToken());
fn(startX, startY, endX, endY);
}
}
public static void fn(int sx, int sy, int ex, int ey){
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{sx, sy});
visited[sx][sy]=true;
while(!q.isEmpty()){
int[] xy = q.poll();
if(xy[0]==ex && xy[1]==ey){
System.out.println(arr[xy[0]][xy[1]]);
return;
}
for(int i=0; i<8; i++){
int nx = xy[0]+dx[i];
int ny = xy[1]+dy[i];
if(nx<0 || nx>=size || ny<0 || ny>=size || visited[nx][ny])
continue;
q.add(new int[]{nx, ny});
visited[nx][ny] = true;
arr[nx][ny] = arr[xy[0]][xy[1]]+1;
}
}
}
}