체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까?
입력
입력의 첫째 줄에는 테스트 케이스의 개수가 주어진다.
각 테스트 케이스는 세 줄로 이루어져 있다. 첫째 줄에는 체스판의 한 변의 길이 l(4 ≤ l ≤ 300)이 주어진다. 체스판의 크기는 l × l이다. 체스판의 각 칸은 두 수의 쌍 {0, ..., l-1} × {0, ..., l-1}로 나타낼 수 있다. 둘째 줄과 셋째 줄에는 나이트가 현재 있는 칸, 나이트가 이동하려고 하는 칸이 주어진다.
출력
입력의 첫째 줄에는 테스트 케이스의 개수가 주어진다.
각 테스트 케이스는 세 줄로 이루어져 있다. 첫째 줄에는 체스판의 한 변의 길이 l(4 ≤ l ≤ 300)이 주어진다. 체스판의 크기는 l × l이다. 체스판의 각 칸은 두 수의 쌍 {0, ..., l-1} × {0, ..., l-1}로 나타낼 수 있다. 둘째 줄과 셋째 줄에는 나이트가 현재 있는 칸, 나이트가 이동하려고 하는 칸이 주어진다.
예제 입력 1
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
예제 출력 1
5
28
0
풀이
기본적은 BFS문제 였고, 데스 나이트 문제를 생각하면서 어렵지 않게 해결 성공!
import 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;
}
}
}
}