![[백준 C++] 7562 : 나이트의 이동](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FssIMm%2FbtsKOzXhC7N%2FgX5jv0nqETEH9V5TvSQPI0%2Fimg.png)
[백준 C++] 7562 : 나이트의 이동CSE/코딩 문제풀이2024. 11. 19. 14:21
Table of Contents
https://www.acmicpc.net/problem/7562
문제에서 주어진 내용에 있는 '최소 몇 번' 이라는 문구를 보고 BFS로 풀었다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> answer;
vector<vector<bool>> visited;
int dx[8] = { -2, -1, 1, 2, -2, -1, 1, 2 };
int dy[8] = { -1, -2, -2, -1, 1, 2, 2, 1 };
void bfs(int X, int Y, int I)
{
queue<pair<int, int>> que;
visited[Y].at(X) = true;
que.push(make_pair(Y, X));
while (!que.empty())
{
int currentY = que.front().first;
int currentX = que.front().second;
que.pop();
for (int i = 0; i < 8; i++)
{
int nextY = currentY + dy[i];
int nextX = currentX + dx[i];
if ((nextY >= 0 && nextY < I) && (nextX >= 0 && nextX < I))
{
if (!visited[nextY].at(nextX))
{
visited[nextY].at(nextX) = true;
answer[nextY].at(nextX) = answer[currentY].at(currentX) + 1;
que.push(make_pair(nextY, nextX));
}
}
}
}
}
int main()
{
int T, I, X, Y, DesX, DesY;
cin >> T;
for (int i = 0; i < T; i++)
{
cin >> I >> X >> Y >> DesX >> DesY;
answer = vector<vector<int>>(I, vector<int>(I, 0));
visited = vector<vector<bool>>(I, vector<bool>(I, false));
bfs(X, Y, I);
cout << answer[DesY].at(DesX) << '\n';
}
return 0;
}
풀이방식은 최근에 풀었던 BFS 문제들과 거의 유사하다.
dx와 dy를 이용해 이동하면서 첫 방문 시 answer에 지나온 길 수를 저장하였다.
'CSE > 코딩 문제풀이' 카테고리의 다른 글
[백준 C++] 1920 : 수 찾기 (0) | 2024.11.21 |
---|---|
[백준 C++] 11866 : 요세푸스 문제 0 (0) | 2024.11.20 |
[백준 C++] 1679 : 숨바꼭질 (0) | 2024.11.18 |
[백준 C++] 2178 : 미로 탐색 (0) | 2024.11.17 |
[백준 C++] 1012 : 유기농 배추 (2) | 2024.11.16 |
@NiffJB :: 개발하는 니프
CSE & GAME 개발 블로그
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 부탁드립니다!