์๊ณ ๋ฆฌ์ฆ
๋ฐฑ์ค_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;
}