迷宫寻路(bfs)
第一次写博客,希望能把基础的算法记录下来,以后快要忘记了可以拿来复习。
题目:
输入输出要求:
样例:
输入样例:
8 8
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 0
0 1 1 1 0 1 1 0
1 0 0 0 0 0 0 0
4 4
0 0 1 0
0 0 0 0
0 0 1 1
0 1 0 0
-1 -1
输出样例:
1,1
2,1
3,1
4,1
5,1
5,2
5,3
6,3
6,4
6,5
7,5
8,5
8,6
8,7
8,8
NO FOUND
思路:
广度优先搜索,找到出路。
使用队列,逐层寻找出路。
具体实现:先将起点push进队列里,然后将四个方向能够走的位置push进队列里,并且把起点pop出去。然后将队列中的第一个结点当作起点重复操作。
为了防止走回头路,每push进队列中一个位置,就要一个vis数组标记上,下次检测到这个位置也不再走这个位置。
注意:
这个题需要输出路径,所以需要一个数组来记录路径。
就是用一个数组标记上每个位置的父亲位置,虽然每个父亲位置可能有很多子位置,但每个子位置只有一个父亲位置。所以可以从最后一个位置开始倒推出路径。
我第一次用的栈,内存超限了,又用了个递归,然后经过了无数次创造bug,找bug,最后过了。(格式错误真的很烦,这个里面要求输出no found的时候不用空一行了)
代码:
#include<iostream>
#include<stack>
#include<queue>
#include<string.h>
using namespace std;
const int maxx=50;
struct Point{
int x;
int y;
};
Point fu[maxx][maxx];
queue<Point> q;
int go[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int map[maxx][maxx],cnt;
//int vis[10][10]={0};
int m,n;
int pan(int xx,int yy){
if(xx>=0&&xx<m&&yy>=0&&yy<n){
return 1;
}
return 0;
}
int bfs(){
//vis[0][0]=1;
map[0][0]=1;
Point a;
a.x=0;
a.y=0;
q.push(a);
while(!q.empty()){
Point head=q.front();
q.pop();
int xx=head.x;
int yy=head.y;
if(xx==m-1&&yy==n-1){
return 1;
}
for(int i=0;i<4;i++){
int nextx=xx+go[i][0];
int nexty=yy+go[i][1];
Point next;
next.x=nextx;
next.y=nexty;
if(pan(nextx,nexty)&&!map[nextx][nexty]){
map[nextx][nexty]=1;
fu[nextx][nexty]=head;//记录路径
q.push(next);
}
}
}
return 0;
}
/*inline void printlu(){
// cout<<"yes"<<endl;
stack<Point> s;
Point zhong;
zhong.x=m-1;
zhong.y=n-1;
s.push(zhong);
for(int i=m-1,j=n-1;;){
if(fu[i][j].x==0&&fu[i][j].y==0){
break;
}
s.push(fu[i][j]);
int t=i;
i=fu[i][j].x;
j=fu[t][j].y;
}
Point qi;
qi.x=0;
qi.y=0;
s.push(qi);
while(!s.empty()){
Point p;
p=s.top();
cout<<p.x+1<<","<<p.y+1<<endl;
s.pop();
}
}*/
void printlu(Point p){
if(p.x==0&&p.y==0){
cout<<p.x+1<<","<<p.y+1;
}else{
printlu(fu[p.x][p.y]);
cout<<p.x+1<<","<<p.y+1;
}
cout<<endl;
}
int main(){
while(cin>>m>>n&&m!=-1){
// memset(vis,0,sizeof(vis));
// memset(map,0,sizeof(map));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
cin>>map[i][j];
}
}
if(!bfs()){
cout<<"NO FOUND"<<endl;
}else{
Point t;
t.x=m-1;
t.y=n-1;
printlu(t);
cout<<endl;
}
}
return 0;
}
go数组是用来算下一个位置的。
pan函数是判断位置是否越界(走出迷宫了)。
注释掉的部分是用stack输出的方法,出来的答案是对了,但是内存超限了,害。
后边的printlu函数递归输出路径(因为咱们是从后往前保存路径的)