코딩성장스토리

백준:7562번 나이트의 이동 본문

백준 코딩

백준:7562번 나이트의 이동

까르르꿍꿍 2022. 3. 18. 18:53

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

 

7562번: 나이트의 이동

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

www.acmicpc.net

 

 

BFS로 풀면 그게 곧 최소 거리이므로 목적지 도달할 떄 탈출하면 된다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> pii;
int arr[301][301];
bool check[301][301];
int dx[] = { 1,2,-1,-2,1,2,-1,-2 };
int dy[] = { 2,1,2,1,-2,-1,-2,-1 };
int t, l, startx,starty,endx,endy;

void reset(int l) {
	for (int i = 0; i < l; i++) {
		for (int k = 0; k < l; k++) {
			arr[i][k] = 0;
			check[i][k] = false;
		}
	}
}
int bfs(int x, int y) {
	
	queue<pii> p;
	p.push(pii(x, y));
	while (!p.empty()) {
		x = p.front().first;
		y = p.front().second;
		int before = arr[y][x];
		if (x == endx && y == endy) {
			return arr[endy][endx];
		}
		p.pop();
		for (int i = 0; i < 8; i++) {
			int nx = x + dx[i];
			int ny = y + dy[i];
			if (nx >= 0 && nx < l && ny >= 0 && ny < l) {
				if (!check[ny][nx]) {
					p.push(pii(nx, ny));
					check[ny][nx] = true;
					arr[ny][nx] = before + 1;
				}
			}
		}
	}
}

int main()	
{
	cin >> t;
	while (t--) {
		cin >> l;
		cin >> startx >> starty;
		cin >> endx >> endy;
		bfs(startx, starty);
		cout << arr[endy][endx] << '\n';
		reset(l);
	}
}

'백준 코딩' 카테고리의 다른 글

백준 1904번 : 01타일  (0) 2022.06.02
백준 13305번: 주유소  (0) 2022.04.25
백준 2583번 : 영역 구하기  (0) 2022.03.18
백준 1697번:숨바꼭질  (0) 2022.02.07
백준 1182번: 부분수열의 합  (0) 2022.02.06