-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
65 lines (53 loc) · 1.52 KB
/
Main.java
File metadata and controls
65 lines (53 loc) · 1.52 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Queue;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static int[] dx = {-2,-1,1,2,2,1,-1,-2};
static int[] dy = {-1,-2,-2,-1,1,2,2,1};
static boolean[][] map;
static int I;
static Point end;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for(int t=0; t<tc; t++){
I = sc.nextInt();
map = new boolean[I][I];
int sx = sc.nextInt();
int sy = sc.nextInt();
end = new Point(sc.nextInt(), sc.nextInt(), 0);
bfs(sx, sy);
}
sc.close();
}
public static void bfs(int x, int y){
Queue<Point> q = new LinkedList<>();
q.add(new Point(x,y,0));
map[x][y] = true;
while(!q.isEmpty()) {
Point p = q.poll();
if(p.x == end.x && p.y == end.y){
System.out.println(p.dept);
return;
}
for(int i=0; i<8; i++){
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if(0<=nx && nx<I && 0<=ny && ny<I){
if(!map[nx][ny]){
map[nx][ny] = true;
q.add(new Point(nx, ny, p.dept+1));
}
}
}
}
}
}
class Point {
int x, y, dept;
public Point(int x, int y, int dept){
this.x = x;
this.y = y;
this.dept = dept;
}
}