#유형 : 그래프, BFS
# BFS의 기본 문제중 한 가지. 기존의 다른 탐색문제에서 나이트의 이동 범위만 수정해주면 해결할 수 있다.
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
|
package bj;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class p7562 {
static int moveX[] = {1,2,2,1,-1,-2,-2,-1};
static int moveY[] = {-2,-1,1,2,2,1,-1,-2};
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine());
for(int t=0; t<tc; t++) {
int n = Integer.parseInt(br.readLine());
int arr[][] = new int[n][n];
int currentX, currentY, targetX, targetY;
StringTokenizer st = new StringTokenizer(br.readLine());
currentX = Integer.parseInt(st.nextToken());
currentY = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
targetX = Integer.parseInt(st.nextToken());
targetY = Integer.parseInt(st.nextToken());
Point start = new Point(currentX,currentY);
Point target = new Point(targetX, targetY);
bfs(start, target, arr);
}
}
private static void bfs(Point start, Point target, int[][] arr) {
// TODO Auto-generated method stub
Queue<Point> queue =new LinkedList<Point>();
queue.add(start);
boolean visit[][] = new boolean[arr.length][arr.length];
visit[start.y][start.x] = true;
while(!queue.isEmpty()) {
Point p = queue.poll();
if(p.y==target.y && p.x==target.x) {
System.out.println(arr[p.y][p.x]);
return;
}
for(int d=0; d<8; d++) {
int newY = p.y + moveY[d];
int newX = p.x + moveX[d];
if(0<=newX && newX<arr.length && 0<=newY && newY<arr.length && !visit[newY][newX]) {
visit[newY][newX] = true;
arr[newY][newX] = arr[p.y][p.x] + 1;
queue.add(new Point(newX,newY));
}
}
}
}
}
|
cs |
'백준' 카테고리의 다른 글
#백준_10026 적록색약 - Java 자바 (0) | 2020.02.13 |
---|---|
#백준_1325 효율적인 해킹 - Java 자바 (0) | 2020.02.12 |
#백준_2573 빙산 - Java 자바 (0) | 2020.02.10 |
#백준_1062 가르침 - Java 자바 (0) | 2020.02.10 |
#백준_7569 토마토 - Java 자바 (0) | 2020.02.09 |