[Link] https://www.acmicpc.net/problem/7562
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
Queue<int[]> q = new LinkedList<>();
int[][] step;
int tot = toi(br.readLine());
int[] di = new int[] {1, 2}, dj = new int[] {2, 1}, sign = new int[] {1, -1};
loop:
for(int i = 0; i < tot; i++) {
q.clear();
int l = toi(br.readLine());
int[] orig = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] dest = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
if(orig[0] == dest[0] && orig[1] == dest[1]) {
sb.append("0\n");
continue;
}
step = new int[l][l];
q.add(orig);
while(!q.isEmpty()) {
int[] bottom = q.poll();
for(int j = 0; j < 2; j++) { // sign i
for(int k = 0; k < 2; k++) { //sign j
for(int m = 0; m < 2; m++) {
int ii = bottom[0] + sign[j] * di[m], jj = bottom[1] + sign[k] * dj[m];
if(ii < 0 || ii >= l || jj < 0 || jj >= l || step[ii][jj] != 0) continue;
if(ii == dest[0] && jj == dest[1]) {
sb.append(step[bottom[0]][bottom[1]] + 1).append("\n");
continue loop;
}
q.add(new int[]{ ii, jj });
step[ii][jj] = step[bottom[0]][bottom[1]] + 1;
}
}
}
}
}
print(sb);
}
static int toi(String s) { return Integer.parseInt(s); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}