문제 URL : https://www.acmicpc.net/problem/16948
문제 접근법 : 문제는 아주 쉽습니다.
bfs를 이용할줄 알고 bfs로 문제 조건대로 갈수있는 방향을 가면 되기 때문에
그대로 하드 코딩해도 문제가 쉽게 풀립니다. 굳이 하나 제약조건 이있다면 범위가 좌표 범위가 0<=y<n , 0<= x<n 이라는것 외에는 따로 설명드릴게 없습니다.
소스코드 :
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
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int visit[201][201];
int r1, c1, r2, c2;
int n;
int dy[6] = { -2, -2, 0, 0, 2, 2 };
int dx[6] = { -1, 1, -2, 2, -1, 1 };
bool isrange(int y, int x)
{
if (0 <= y&&y < n && 0 <= x&&x < n)
return true;
return false;
}
int bfs()
{
int cnt = 0;
queue<pair<int, int>> q;
q.push({ r1, c1 });
visit[r1][c1] = 1;
while (!q.empty())
{
int qsize = q.size();
while (qsize--){
int y = q.front().first;
int x = q.front().second;
q.pop();
if (y == r2&&x == c2)//도착지점
return cnt;
for (int i = 0; i < 6; i++){
int ny = y + dy[i];
int nx = x + dx[i];
if (isrange(ny, nx) && !visit[ny][nx]){
visit[ny][nx] = 1;
q.push({ ny, nx });
}
}
}
cnt++;
}
return -1;//갈수없음
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
cin >> r1 >> c1 >> r2 >> c2;
cout << bfs() << "\n";
}
|
cs |
궁금한점이나 모르는 점이있따면 언제든지 댓글을 이용해주시길 바랍니다.
'백준' 카테고리의 다른 글
백준 16197 두 동전 (0) | 2020.07.31 |
---|---|
백준 14225 부분수열의 합 (0) | 2020.07.31 |
백준 1463 1로 만들기 (0) | 2020.07.27 |
백준 10825 국영수 (0) | 2020.07.27 |
백준 17834 사자와 토끼 (0) | 2020.07.26 |