《迷宫问题》题解
2025-05-10 09:43:16
发布于:上海
2阅读
0回复
0点赞
废话不多说,代码如下:
#include<bits/stdc++.h>
using namespace std;
int n,m,b[50][50];
int mp[50][50];
int dx[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
struct node{
int x,y,step;
}l,r;
int main(){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
cin>>mp[i][j];
}
}
queue<node>q;
q.push({1,1,0});
b[1][1]=1;
while(q.size()){
r=q.front();
q.pop();
if(r.x==5 && r.y==5){
cout<<r.step; //迷宫问题有些算起点,有些不算,根据实际情况修改即可
return 0;
}
for(int i=0;i<4;i++){
l.x=r.x+dx[i][0];
l.y=r.y+dx[i][1];
l.step=r.step+1;
if(l.x>=1 && l.x<=5 && l.y>=1 && l.y<=5 && b[l.x][l.y]!=1 && mp[l.x][l.y]==0){
b[l.x][l.y]=1;
q.push(l);
}
}
}
cout<<-1;
return 0;
}
这里空空如也
有帮助,赞一个