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

4108 단어 백준백준

1. 링크

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

2. 풀이

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

const int dy[8] = {-2, -1, 1, 2, -2, -1, 1, 2};
const int dx[8] = {-1, -2, -2, -1, 1, 2, 2, 1};
int check[305][305];

int main() {
    int T;
    cin >> T;

    while (T--) {

        memset(check ,0, sizeof(check));
        int ans;

        int a;
        cin >> a;
        int fromX, fromY, toX, toY;
        cin >> fromX >> fromY >> toX >> toY;

        if (fromX == toX && fromY == toY){
            cout<<"0"<<'\n';
            continue;
        }

        int cnt = 0;
        queue<pair<pair<int, int>, int>> q;
        q.push(make_pair(make_pair(fromX, fromY), cnt));
        check[fromX][fromY]=1;
        
        while (!q.empty()) {

            pair<int, int> tmp = q.front().first;
            int tmpCnt = q.front().second;

            int xx = tmp.first;
            int yy = tmp.second;
            q.pop();

            if (xx == toX && yy == toY) {
                    cout<<tmpCnt<<'\n';
                    break;
                }
                
                
            for (int i = 0; i < 8; i++) {
                int nx = xx + dx[i];
                int ny = yy + dy[i];

                
                if (nx < 0 || nx >= a || ny < 0 || ny >= a) continue;
                if (check[nx][ny]==1) continue;


                    check[nx][ny]=1;
                    q.push(make_pair(make_pair(nx, ny), tmpCnt + 1));
                
            }

        }
        // ans 
    }

}

좋은 웹페이지 즐겨찾기