백준 문제/BFS

[백준] 7562번 나이트의 이동

dubu0721 2025. 1. 14. 15:20

문제: 7562번: 나이트의 이동

basic-algo-lecture/workbook/0x09.md at master · encrypted-def/basic-algo-lecture

 

basic-algo-lecture/workbook/0x09.md at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

 

#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iomanip> // setprecision을 사용하기 위한 헤더
#include <climits>
#include <list>

using namespace std;


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

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

    int t;
    cin >> t;
    while (t-- > 0) {
        int l; // 체스판 한 변 길이
        cin >> l;

        vector<vector<int>> board(l);
        vector<vector<int>> visit(l);
        vector<vector<int>> dist(l);
        for (int i = 0; i < l; i++) {
            board[i] = vector<int>(l);
            visit[i] = vector<int>(l);
            dist[i] = vector<int>(l);
        }

        queue<pair<int, int>> nexts;
        int curX, curY;
        cin >> curX >> curY;
        pair<int, int> cur = make_pair(curX, curY);
        visit[curX][curY] = 1; // 방문 표시
        dist[curX][curY] = 0;
        nexts.push(cur);

        int tarX, tarY;
        cin >> tarX >> tarY;
        pair<int, int> target = make_pair(tarX, tarY); // 목표지점

        while (!nexts.empty()) {
            pair<int, int> cur = nexts.front();
            nexts.pop();
            if (cur.first == tarX && cur.second == tarY) {
                cout << dist[cur.first][cur.second] << "\n";
                break;
            }

            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 (visit[nx][ny] == 1) continue;

                dist[nx][ny] = dist[cur.first][cur.second] + 1;
                visit[nx][ny] = 1; // 방문 표시
                nexts.push(make_pair(nx, ny));
            }
        }
    }
   
    return 0;
}

 

BFS 기본문제. 그냥 방향이 8개가 되었다는 것 빼고는 상하좌우로 이동할 수 있는 BFS 문제와 다를 바가 없다.

 

현재 위치가 목표 위치와 같다면 거리(이동 시간)를 출력하고 while 문에서 빠져나오면 된다.

 

 

 

참고자료:

BaaaaaaaarkingDog | [실전 알고리즘] 0x09강 - BFS

 

[실전 알고리즘] 0x09강 - BFS

안녕하세요 여러분, 드디어 올 것이 왔습니다. 마음의 준비를 단단히 하셔야 합니다.. 드디어 실전 알고리즘 강의에서 첫 번째 고비에 도달했는데 이 강의와 함께 이번 고비를 잘 헤쳐나가면 좋

blog.encrypted.gg