4. BFS
[BFS] 백준 7562번 - 나이트의 이동 (정답률 44%)
asdklfjlasdlfkj
2020. 1. 7. 18:44
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
문제 체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까? 입력 입력의 첫째 줄에는 테스트 케이스의 개수가 주어진다. 각 테스트 케이스는 세 줄로 이루어져 있다. 첫째 줄에는 체스판의 한 변의 길이 l(4 ≤ l ≤ 300)이 주어진다. 체스판의 크기는 l × l이다. 체스판의 각 칸은 두 수의 쌍 {0, ...
www.acmicpc.net
BFS 알고리즘 연습 문제이다.
나이트가 갈 수 있는 방향 8개가 주어지고, 현재 위치와 목표로 하는 위치가 주어졌을 때, 몇 번만에 목적지로 이동할 수 있는지 묻는 문제였다. 전형적인 BFS 문제로, 현 위치에서 갈 수 있는 방향으로 가지를 각각 뻗어나가며 정답에 도달하는 경우 종료하는 알고리즘을 사용했다.
아래는 BFS 소스코드. (20ms)
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
|
#include <iostream>
#include <queue>
#define maxlen 300
using namespace std;
int l; // 0, 1, ..., l-1
int start_r, start_c, target_r, target_c;
int map[maxlen][maxlen]; // 0 ~ 299.
bool check[maxlen][maxlen];
int answer;
typedef struct dir{
int dr, dc;
}dir;
dir direction[8] = { { 1, 2 }, { 2, 1 }, { -1, 2 }, { 1, -2 }, { -1, -2 }, { -2, 1 }, { 2, -1 }, { -2, -1 } };
// 나이트가 갈 수 있는 방법 8가지.
void reset(){
for (int i = 0; i < maxlen; i++)
for (int j = 0; j < maxlen; j++){
map[i][j] = 0; // 초기화.
check[i][j] = false; // 초기화
}
}
void bfs(int row, int col, int curtime){
queue<pair<int, pair<int, int> > > q;
check[row][col] = true;
q.push(make_pair(curtime, make_pair(row, col)));
while (!q.empty()){
int cur_time = q.front().first;
if (cur_row == target_r && cur_col == target_c){ // 정답 찾음.
answer = cur_time;
break;
}
q.pop();
for (int i = 0; i < 8; i++){
int n_r = cur_row + direction[i].dr;
int n_c = cur_col + direction[i].dc;
if (n_r >= 0 && n_r < l && n_c >= 0 && n_c < l)
{
if (!check[n_r][n_c]){
check[n_r][n_c] = true;
q.push(make_pair(cur_time + 1, make_pair(n_r, n_c)));
}
}
}
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int TC;
cin >> TC;
for (int i = 0; i < TC; i++){
reset();
cin >> l;
cin >> start_r >> start_c;
cin >> target_r >> target_c;
bfs(start_r, start_c, 0);
cout << answer << '\n';
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |