7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int d[300][300];
int dx[] = {-2,-1,1,2,2,1,-1,-2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        int sx,sy;
        cin >> sx >> sy;
        int ex,ey;
        cin >> ex >> ey;
        memset(d,-1,sizeof(d));
        queue<pair<int,int>> q;
        q.push(make_pair(sx,sy));
        d[sx][sy] = 0;
        while (!q.empty()) {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
            for (int k=0; k<8; k++) {
                int nx = x+dx[k];
                int ny = y+dy[k];
                if (0 <= nx && nx < n && 0 <= ny && ny < n) {
                    if (d[nx][ny] == -1) {
                        d[nx][ny] = d[x][y] + 1;
                        q.push(make_pair(nx,ny));
                    }
                }
            }
        }
        cout << d[ex][ey] << '\n';
    }
    return 0;
}

'Problem set' 카테고리의 다른 글

[백준] 16964 DFS 스페셜 저지  (0) 2021.02.20
[백준] 16940 BFS 스페셜 저지  (0) 2021.02.20
[백준] 7576 토마토  (0) 2021.02.20
[백준] 2178 미로 탐색  (0) 2021.02.20
[백준] 4963 섬의 개수  (0) 2021.02.20
복사했습니다!