BFS 迷宫 最少步数
#include<bits/stdc++.h> using namespace std; struct node { int x,y; int step; node() {}; node(int a,int b,int c):x(a),y(b),step(c) { } } s,t; const int Max=100; int n,m; char M[Max][Max]; bool a[Max][Max]= {0}; int X[4]= {1,0,-1,0}; int Y[4]= {0,-1,0,1}; bool Judge(int x,int y) { if(x<0||x>=n||y<0||y>=m) { return 0; } if(M[x][y]=='*'||a[x][y]==1) { return 0; } return 1; } void BFS(int x,int y) { queue<node> q; q.emplace(node(x,y,0)); a[x][y]=1; while(!q.empty()) { node b=q.front(); q.pop(); if(b.x==t.x&&b.y==t.y) { cout<<b.step<<endl;; } for(int i=0; i<4; i++) { int newx=b.x+X[i]; int newy=b.y+Y[i]; if(Judge(newx,newy)) { q.emplace(node(newx,newy,b.step+1)); a[newx][newy]=1; } } } return ; } int main() { while(cin>>n>>m) { for(int i=0; i<n; i++) { for(int j=0; j<m; j++) { cin>>M[i][j]; } } cin>>s.x>>s.y>>t.x>>t.y; BFS(s.x,s.y); } return 0; }
法2
#include<bits/stdc++.h>
using namespace std;struct node {
int x,y;
int step;
node() {};
node(int a,int b,int c):x(a),y(b),step(c) {
}
} s,t;
const int Max=100;
int n,m;
char M[Max][Max];
bool a[Max][Max]= {0};
int X[4]= {1,0,-1,0};
int Y[4]= {0,-1,0,1};
bool Judge(int x,int y) {
if(x<0||x>=n||y<0||y>=m) {
return 0;
}
if(M[x][y]=='*'||a[x][y]==1) {
return 0;
}
return 1;
}
void BFS(int x,int y) {
queue<node> q;
q.emplace(node(x,y,0));
a[x][y]=1;
while(!q.empty()) {
node b=q.front();
q.pop();
if(b.x==t.x&&b.y==t.y) {
cout<<b.step<<endl;;
}
for(int i=0; i<4; i++) {
int newx=b.x+X[i];
int newy=b.y+Y[i];
if(Judge(newx,newy)) {
q.emplace(node(newx,newy,b.step+1));
a[newx][newy]=1;
}
}
}
return ;
}
int main() {
while(cin>>n>>m) {
for(int i=0; i<n; i++) {
getchar();
for(int j=0; j<m; j++) {
M[i][j]=getchar();
}
M[i][m+1]='\0';
}
cin>>s.x>>s.y>>t.x>>t.y;
BFS(s.x,s.y);
}
return 0;
}