bfs
2025-08-05 10:19:04
发布于:北京
1阅读
0回复
0点赞
#include<iostream>
#include<queue>
using namespace std;
const int N = 6;
int a[N][N];
bool vis[N][N];
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool check(int x, int y){
return x>=1&&x<=5&&y>=1&&y<=5&&a[x][y]==0&&!vis[x][y];
}
struct node{
int x, y, step;
};
int main(){
bool flag = true;
for(int i=1; i<=5; i++){
for(int j=1; j<=5; j++){
cin >> a[i][j];
}
}
queue<node> q;
q.push({1, 1});
int step=-1;
while(q.size()){
node u = q.front();
q.pop();
if(u.x==5&&u.y==5){
flag=false;
cout << u.step;
break;
}
for(int i=0; i<4; i++){
int nx = u.x + dx[i];
int ny = u.y + dy[i];
if(check(nx, ny)){
vis[nx][ny] = true;
q.push({nx, ny, u.step+1});
}
}
}
if(flag)cout << -1;
return 0;
}
这里空空如也
有帮助,赞一个