์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฐฑ์ค€_16948_๋ฐ์Šค ๋‚˜์ดํŠธ

shj718 2022. 6. 16. 16:22

๐Ÿ™‹‍โ™€๏ธ ๋ฌธ์ œ

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

 

16948๋ฒˆ: ๋ฐ์Šค ๋‚˜์ดํŠธ

๊ฒŒ์ž„์„ ์ข‹์•„ํ•˜๋Š” ํ๋ธŒ๋Ÿฌ๋ฒ„๋Š” ์ฒด์Šค์—์„œ ์‚ฌ์šฉํ•  ์ƒˆ๋กœ์šด ๋ง "๋ฐ์Šค ๋‚˜์ดํŠธ"๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค. ๋ฐ์Šค ๋‚˜์ดํŠธ๊ฐ€ ์žˆ๋Š” ๊ณณ์ด (r, c)๋ผ๋ฉด, (r-2, c-1), (r-2, c+1), (r, c-2), (r, c+2), (r+2, c-1), (r+2, c+1)๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. ํฌ

www.acmicpc.net

 

๐Ÿงฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ฌธ์ œ์˜ ๋ชฉ์ : ๋ชจ๋“  ์ •์  ๋ฐฉ๋ฌธ, ์ตœ๋‹จ๊ฑฐ๋ฆฌ ๊ตฌํ•˜๊ธฐ → BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ•œ ์นธ(์ •์ )์—์„œ ๋‹ค๋ฅธ ์นธ(์ •์ )์œผ๋กœ ์ด๋™ํ•  ๋•Œ 1๋ฒˆ ์ด๋™ํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ๋ชจ๋“  ๊ฐ€์ค‘์น˜๊ฐ€ 1์ธ ๋ฌธ์ œ  BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

๐Ÿ’ก ์•„์ด๋””์–ด

ํ”ํ•œ ์œ ํ˜•์˜ ๋ฌธ์ œ๋กœ, dx ๋ฐฐ์—ด๊ณผ dy ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ด์„œ ์–ด๋ ต์ง€ ์•Š๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Œ

 

๐Ÿ‘ฉ‍๐Ÿ’ป ์ฝ”๋“œ

#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

int n;
int r1, c1, r2, c2;
bool visited[200][200];
int dist[200][200];
int dx[6] = { -2, -2, 0, 0, 2, 2 };
int dy[6] = { -1, 1, -2, 2, -1, 1 };

void bfs() {
	queue<pair<int, int>> q;
	q.push(make_pair(r1, c1));
	visited[r1][c1] = true;

	while (!q.empty()) {
		pair<int, int> x = q.front(); q.pop();
		for (int i = 0; i < 6; i++) {
			int nx = x.first + dx[i];
			int ny = x.second + dy[i];
			if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
			if (!visited[nx][ny]) {
				q.push(make_pair(nx, ny));
				visited[nx][ny] = true;
				dist[nx][ny] = dist[x.first][x.second] + 1;
			}
		}
	}
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n;
	cin >> r1 >> c1 >> r2 >> c2;
	bfs();
	if (dist[r2][c2] == 0) dist[r2][c2] = -1;
	cout << dist[r2][c2] << '\n';
	return 0;
}