본문 바로가기

알고리즘/BOJ

7562번

7562번 - 나이트의 이동


나이트가 한번에 이동할 수 있는 경로를 모두 체크하는 dx,dy 배열을 만들고


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
#include<iostream>
#include<queue>
using namespace std;
 
int dx[8= { 1,2,2,1,-1,-2,-2,-1 };
int dy[8= { -2,-1,1,2,2,1,-1,-2 };
 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int tc;
    cin >> tc;
 
    for (int t = 1; t <= tc; t++)
    {
        int n, sx, sy, ex, ey;
        int dist[301][301= { 0, };
        cin >> n >> sx >> sy >> ex >> ey;
 
        queue<pair<intint>> q;
        q.push({ sx,sy });
 
        while (!q.empty())
        {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
 
            if (x == ex && y == ey)
            {
                break;
            }
 
            for (int d = 0; d < 8; d++)
            {
                int nx = x + dx[d];
                int ny = y + dy[d];
                if (nx >= 0 && ny >= 0 && nx < n && ny < n && dist[nx][ny] == 0)
                {
                    dist[nx][ny] = dist[x][y] + 1;
                    q.push({ nx,ny });
                }
            }
        }
 
        cout << dist[ex][ey] << "\n";
        
        
    }
    return 0;
}
cs


반응형

'알고리즘 > BOJ' 카테고리의 다른 글

2206번  (0) 2018.03.07
2589번  (0) 2018.03.07
1244. 최대 상금  (0) 2018.03.06
1074번  (0) 2018.02.28
2164번  (0) 2018.02.27