출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 7562 나이트의 이동(bfs)

알고리즘

by 장동균 2020. 8. 5. 01:18

본문

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

 

7562번: 나이트의 이동

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

www.acmicpc.net

#include <iostream>
#include <queue>

using namespace std;
const int MAX = 300;
bool visited[MAX][MAX];
typedef struct
{
    int x, y;
} Dir;
Dir dirMove[8] = {{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
typedef struct
{
    int x, y, cnt;
} point;

int l;
int start_X, start_Y, end_X, end_Y;

int bfs(int x, int y)
{
    visited[x][y] = true;
    queue<point> q;
    q.push({x, y, 0});
    while (!q.empty())
    {
        int curX = q.front().x;
        int curY = q.front().y;
        int curCnt = q.front().cnt;
        q.pop();
        if (curX == end_X && curY == end_Y)
        {
            while (!q.empty())
                q.pop();
            return curCnt;
        }
        for (int i = 0; i < 8; i++)
        {
            int nextX = curX + dirMove[i].x;
            int nextY = curY + dirMove[i].y;
            if (0 <= nextX && nextX < l && 0 <= nextY && nextY < l && !visited[nextX][nextY])
            {
                visited[nextX][nextY] = true;
                q.push({nextX, nextY, curCnt + 1});
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int testcase;
    cin >> testcase;
    while (testcase--)
    {
        cin >> l;

        cin >> start_X >> start_Y;
        cin >> end_X >> end_Y;
        cout << bfs(start_X, start_Y) << "\n";
        for (int i = 0; i < MAX; i++)
        {
            for (int j = 0; j < MAX; j++)
            {
                visited[i][j] = false;
            }
        }
    }
}

관련글 더보기

댓글 영역