728x90
https://www.acmicpc.net/problem/7562
문제
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까?
입력
입력의 첫째 줄에는 테스트 케이스의 개수가 주어진다.
각 테스트 케이스는 세 줄로 이루어져 있다. 첫째 줄에는 체스판의 한 변의 길이 l(4 ≤ l ≤ 300)이 주어진다. 체스판의 크기는 l × l이다. 체스판의 각 칸은 두 수의 쌍 {0, ..., l-1} × {0, ..., l-1}로 나타낼 수 있다. 둘째 줄과 셋째 줄에는 나이트가 현재 있는 칸, 나이트가 이동하려고 하는 칸이 주어진다.
출력
각 테스트 케이스마다 나이트가 최소 몇 번만에 이동할 수 있는지 출력한다.
풀이 방법
최소 이동횟수를 구하기 위해서 BFS를 이용하였고,
시작점과 도착점이 명확하므로 break 지점을 설정하기가 가능하다.
list를 이용하여 값을 삽입 후 마지막에 배열의 요소들을 한번에 출력하였다.
작성 코드
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package baekjoon.graphTraversal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BJ_7562 {
static int T, l;
static int arr[][];
static int x1, x2, y1, y2;
static int D[][] = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
static boolean visited[][];
static ArrayList list = new ArrayList();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
T = Integer.parseInt(br.readLine()); // 테스트 케이스 수
for (int i = 0; i < T; i++) {
l = Integer.parseInt(br.readLine()); // 한변의 길이
arr = new int[l][l];
visited = new boolean[l][l];
StringTokenizer st = new StringTokenizer(br.readLine());
x1 = Integer.parseInt(st.nextToken());
y1 = Integer.parseInt(st.nextToken());
StringTokenizer st2 = new StringTokenizer(br.readLine());
x2 = Integer.parseInt(st2.nextToken());
y2 = Integer.parseInt(st2.nextToken());
BFS(x1, y1);
}
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
}
public static void BFS(int x, int y) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{x, y});
visited[x][y] = true;
while (!q.isEmpty()) {
int now[] = q.poll();
int bx = now[0];
int by = now[1];
if (bx == x2 && by == y2) {
list.add(arr[bx][by]);
break;
}
for (int i = 0; i < 8; i++) {
int ax = bx + D[i][0];
int ay = by + D[i][1];
if (ax >= 0 && ay >= 0 && ax < l && ay < l) {
if (arr[ax][ay] == 0 && visited[ax][ay] == false) {
arr[ax][ay] = arr[bx][by] + 1;
q.add(new int[]{ax, ay});
}
}
}
}
}
}
|
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2583번 : 영역 구하기 (0) | 2021.12.06 |
---|---|
[백준] 2206번 : 벽 부수고 이동하기 (0) | 2021.12.06 |
[백준] 7569번 : 토마토 (0) | 2021.12.03 |
[백준] 10026번 : 적록색약 (0) | 2021.12.02 |
[백준] 1987번 : 알파벳 (0) | 2021.12.02 |