출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
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;
}
}
}
}
백준 2644 촌수계산(bfs) (0) | 2020.08.11 |
---|---|
백준 2250 트리의 높이와 너비(dfs, inorder traversal) (0) | 2020.08.06 |
백준 1613 역사(floyd-warshall) (0) | 2020.08.04 |
백준 9205 맥주 마시면서 걸어가기(dfs) (0) | 2020.08.04 |
백준 2668 숫자고르기(dfs with cycle graph) (0) | 2020.08.03 |
댓글 영역