[백준 알고리즘]/[C++]
7562번 나이트의 이동 | BFS | Baekjoon BOJ 백준 7562 C++ 코드, 해설, 풀이
말하는펭귄
2021. 2. 3. 11:13
728x90
반응형
이번 포스팅은 백준 7562번 나이트의 이동입니다.
아래 url를 클릭하시면 백준 사이트에서 문제를 볼 수 있습니다.
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
기본 알고리즘
최단 경로 = 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
//백준7562 나이트의이동
#include <iostream>
#include <queue>
using namespace std;
int L;
int a, b, c, d;
const int MAX = 300;
int map[MAX][MAX];
bool visited[MAX][MAX];
int path[MAX][MAX];
int dy[] = {2,1,2,1,-2,-1,-2,-1};
int dx[] = {1,2,-1,-2,1,2,-1,-2};
queue<pair<int, int>> q;
void reset() {
for (int i = 0; i < L; i++) {
for (int j = 0; j < L; j++) {
map[i][j] = 0;
visited[i][j] = 0;
path[i][j] = 0;
}
}
while (!q.empty()) {
q.pop();
}
}
void printPath() {
printf("\n[PATH]\n");
for (int i = 0; i < L; i++) {
for (int j = 0; j < L; j++) {
printf("%2d ", path[i][j]);
}
printf("\n");
}
printf("\n");
}
void BFS(int y, int x) {
visited[y][x] = true;
q.push(make_pair(y, x));
while (!q.empty()) {
int y = q.front().first;
int x = q.front().second;
q.pop();
if (y == c && x == d) break;
for (int i = 0; i < 8; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= L || nx >= L)
continue;
if (visited[ny][nx] == 0) {
visited[ny][nx] = true;
q.push(make_pair(ny, nx));
path[ny][nx] = path[y][x] + 1;
}
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
reset();
cin >> L;
cin >> a >> b >> c >> d;
BFS(a, b);
//printPath();
cout << path[c][d] << endl;
}
}
|
cs |
728x90
반응형