문제 주소:https://www.acmicpc.net/problem/7562
사용한 알고리즘: 너비 우선 탐색 (bfs)
->사용이유:원하는 목적지에 도착하는 최소 횟수이기 때문에 처음에 이동할수 있는 경우의 수를 모두 돌리고
그다음 두번째로 이동할 수 있는 경우의 수를 돌리면서 만약 목적지에 도착한다면 그것이 목적지에 도착할수 있는 최소 이동횟수가 된다
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
struct dir{
int x,y;
};
struct qu{
int x,y,val;
};
dir dx[8]={{-1,2},{1,2},{2,1},{-2,1},{2,-1},{-2,-1},{-1,-2},{1,-2}};
int test;
int len,s_x,s_y,end_x,end_y;
int ch[301][301];
vector<int>res;
int cnt;
queue<qu>q;
void bfs()
{
int x, y;
while(!q.empty()){
x=q.front().x;
y=q.front().y;
cnt=q.front().val;
q.pop();
int nx,ny;
if(x==end_x&&y==end_y){
res.push_back(cnt);
break;
}
for(int i=0;i<8;i++){
nx=x+dx[i].x;
ny=y+dx[i].y;
if(nx>=0&&ny>=0&&nx<len&&ny<len){
if(ch[nx][ny]==0){
ch[nx][ny]=1;
q.push({nx,ny,cnt+1});
}
}
}
}
}
int main(){
cin.tie(0);
cout.tie(0);
std::ios::sync_with_stdio(false);
cin>>test;
//반복 횟수 입력
while(test--){
//체스판 길이 입력
cin>>len;
//시작점의 행과 열값 입력
cin>>s_x>>s_y;
//도착점의 행과 열값 입력
cin>>end_x>>end_y;
//bfs를 사용하기 위해 선언한 큐에 시작점과 이동횟수값을 넣음
q.push({s_x,s_y,0});
bfs();
//도착수의 중복방지를 위해 선언한 배열
memset(ch, 0, sizeof(ch));
while(!q.empty()){
q.pop();
}
}
for(int i=0;i<res.size();i++){
cout<<res[i]<<"\n";
}
return 0;
}
처음에 queue를 전역변수로 선언후, 매번 반복할때마다 queue를 비우지 않아 틀렸다.
여러번 실행할 경우, 변수들의 초기화에 좀더 주의해야 할거 같다.
*더 좋은 풀이가 있다면 같이 공유해요! 궁금한 점 있다면 편하게 댓글남겨주세요 ^ ^