본문 바로가기

ALG/ALG Solve

C++) 백준 7562번 - 나이트의 이동

https://www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

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

www.acmicpc.net

 

#include <bits/stdc++.h>
using namespace std;

int dx[]={-2,-1,1,2,2,1,-1,-2};
int dy[]={1,2,2,1,-1,-2,-2,-1};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);

    int tc;
    cin>>tc;
    while(tc--){
        int board[302][302]={};
        int dist[302][302]={};
        int l,x1,y1,x2,y2;
        queue<pair<int,int> > q;

        cin>>l>>x1>>y1>>x2>>y2;
        if(x1==x2&&y1==y2){
            cout<<0<<"\n";
            continue;
        }

        q.push({x1,y1});
        while(!q.empty()){
            auto cur=q.front(); q.pop();
            for(int i=0;i<8;i++){
                int nx=cur.first+dx[i];
                int ny=cur.second+dy[i];
                if(nx<0||nx>=l||ny<0||ny>=l) continue;
                if(dist[nx][ny]>0) continue;
                q.push({nx,ny});
                dist[nx][ny]=dist[cur.first][cur.second]+1;
                if(nx==x2&&ny==y2){
                    cout<<dist[nx][ny]<<"\n";
                }
            }
        }
    }
    return 0;
}