- toc {:toc}
๋ฌธ์
์ฒด์คํ ์์ ํ ๋์ดํธ๊ฐ ๋์ฌ์ ธ ์๋ค. ๋์ดํธ๊ฐ ํ ๋ฒ์ ์ด๋ํ ์ ์๋ ์นธ์ ์๋ ๊ทธ๋ฆผ์ ๋์์๋ค. ๋์ดํธ๊ฐ ์ด๋ํ๋ ค๊ณ ํ๋ ์นธ์ด ์ฃผ์ด์ง๋ค. ๋์ดํธ๋ ๋ช ๋ฒ ์์ง์ด๋ฉด ์ด ์นธ์ผ๋ก ์ด๋ํ ์ ์์๊น?
์ ๋ ฅ
์ ๋ ฅ์ ์ฒซ์งธ ์ค์๋ ํ ์คํธ ์ผ์ด์ค์ ๊ฐ์๊ฐ ์ฃผ์ด์ง๋ค.
๊ฐ ํ ์คํธ ์ผ์ด์ค๋ ์ธ ์ค๋ก ์ด๋ฃจ์ด์ ธ ์๋ค. ์ฒซ์งธ ์ค์๋ ์ฒด์คํ์ ํ ๋ณ์ ๊ธธ์ด l(4 โคย l โค 300)์ด ์ฃผ์ด์ง๋ค. ์ฒด์คํ์ ํฌ๊ธฐ๋ l ร l์ด๋ค. ์ฒด์คํ์ ๊ฐ ์นธ์ ๋ ์์ ์ {0, โฆ, l-1} ร {0, โฆ, l-1}๋ก ๋ํ๋ผ ์ ์๋ค. ๋์งธ ์ค๊ณผ ์ ์งธ ์ค์๋ ๋์ดํธ๊ฐ ํ์ฌ ์๋ ์นธ, ๋์ดํธ๊ฐ ์ด๋ํ๋ ค๊ณ ํ๋ ์นธ์ด ์ฃผ์ด์ง๋ค.
์ถ๋ ฅ
๊ฐ ํ ์คํธ ์ผ์ด์ค๋ง๋ค ๋์ดํธ๊ฐ ์ต์ ๋ช ๋ฒ๋ง์ ์ด๋ํ ์ ์๋์ง ์ถ๋ ฅํ๋ค.
์ถ์ฒ:https://www.acmicpc.net/problem/7562
ํ์ด
2022-08-07
BFS๋ฅผ ์ด์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ํ์ดํ์ง๋ง ์์น๊ฐ ๋ค๋ฅด๊ธฐ ๋๋ฌธ์ ๋ณํํ๋ dx, dy๊ฐ์ ๋ค๋ฅด๊ฒ ์ค์ ํด์ฃผ๋ฉด ์ด๋ ค์ ์์ด ํ์ด ํ ์ ์๋ค.
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int dist[302][302];
int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};
int l;
pair<int, int> now, target;
queue<pair<int, int>> q;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
while(T--){
cin >> l;
cin >> now.X >> now.Y;
cin >> target.X >> target.Y;
while(!q.empty()){
q.pop();
}
// dist ฤฤฤ
รขฤยญ
for(int i = 0; i < l; i++){
for(int j = 0; j < l; j++){
dist[i][j] = -1;
}
}
q.push({now.X, now.Y});
dist[now.X][now.Y] = 0;
if(now.X == target.X && now.Y == target.Y){
cout << dist[now.X][now.Y] << endl;
continue;
}
for(int i = 0; i < l; i++){
for(int j = 0; j < l; j++){
while(!q.empty()){
auto cur = q.front(); q.pop();
for(int dir = 0; dir < 8; dir++){
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if(nx < 0 || nx >= l || ny < 0 || ny >= l) continue;
if(dist[nx][ny] >= 0) continue;
dist[nx][ny] = dist[cur.X][cur.Y] + 1;
if(target.X == nx && target.Y == ny){
cout << dist[nx][ny] << endl;
break;
}
q.push({nx, ny});
}
}
}
}
}
}2023-09-07 ํ์ด
BFS ๋ฌธ์ ์ธ ๊ฒ์ ์๋ฉด ๊ตฌ์กฐ๋ ์ ํํ๋์ด ์์ด ํ์ด๊ฐ ๋ณํ์ง ์๋ ๊ฒ ๊ฐ๋ค.
#include <bits/stdc++.h>
using namespace std;
#define X first
#define Y second
int dx[8] = {-1, -1, 1, 1, -2, -2, 2, 2};
int dy[8] = {-2, 2, -2, 2, -1, 1, -1, 1};
int T, I;
queue<pair<int, int>> q;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
pair<int, int> start, end;
cin >> T;
while(T--){
int board[303][303] = {0,};
int dist[303][303] = {0,};
cin >> I;
cin >> start.X >> start.Y;
q.push(start);
cin >> end.X >> end.Y;
if (start.X == end.X && start.Y == end.Y) {
cout << 0 << '\n';
continue;
}
while(!q.empty()){
auto cur = q.front(); q.pop();
for(int dir = 0; dir < 8; dir++){
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if(nx < 0 || nx >= I || ny < 0 || ny >= I) continue;
if(dist[nx][ny] > 0) continue;
dist[nx][ny] = dist[cur.X][cur.Y]+1;
if(nx == end.X && ny == end.Y){
cout << dist[nx][ny] << '\n';
break;
}
q.push({nx, ny});
}
}
}
return 0;
}