기본적인 BFS문제.
위, 아래, 왼쪽, 오른쪽으로 움직이던 기존 문제들과는 달리 이번에는 8개의 방향으로 움직인다. 이 표시만 잘해주고 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
|
#include <iostream>
#include <algorithm>
#include <queue>
#define visited true
#define Non_visited false
#define MAX 301
using namespace std;
typedef pair<int,int> pir;
int xx[8]={1,2,2,1,-1,-2,-2,-1};
int yy[8]={2,1,-1,-2,-2,-1,1,2};
bool Check[MAX][MAX];
int cnt[MAX][MAX];
int num;
int k,x,y,targetX,targetY;
queue<int> ans;
void solved(){
queue<pir> p;
p.push(pir(y,x));
Check[y][x]=visited;
while(!p.empty()){
int y=p.front().first;
int x=p.front().second;
p.pop();
if(targetX==x && targetY==y){
ans.push(cnt[y][x]);
break;
}
for(int i=0;i<8;i++){
int ny=y+yy[i];
int nx=x+xx[i];
if(ny<0 || nx<0 || ny>=k || nx>=k) continue;
if(Check[ny][nx]!=visited){
p.push(pir(ny,nx));
Check[ny][nx]=visited;
cnt[ny][nx]=cnt[y][x]+1;
}
}
}
}
void Clear(){
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
cnt[i][j]=0;
Check[i][j]=Non_visited;
}
}
}
int main(){
cin >> num;
while(num--){
cin >> k >> y >> x >> targetY >> targetX;
solved();
Clear();
// fill(Check,Check+k,Non_visited);
}
while(!ans.empty()){
int x=ans.front();
ans.pop();
cout << x << endl;
}
}
|
cs |
'Coding > 백준' 카테고리의 다른 글
| 6593번 상범 빌딩 (0) | 2020.03.08 |
|---|---|
| 1719번 택배 (0) | 2020.03.01 |
| 1956번 운동 (0) | 2020.02.28 |
| 2458번 키 순서 (0) | 2020.02.28 |
| 11054번 가장 긴 바이토닉 부분 수열 (0) | 2020.02.27 |