定义一个二维数组:
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
DFS版本代码<---戳这里
BFS code:
#include<iostream>
#include<queue>
using namespace std;
int a[5][5];
int dirx[4] = {1,-1,0,0};
int diry[4] = {0,0,1,-1};
struct node
{
int x;
int y;
int len;//走到该位置共需几步
int path[25][2];//走到该位置的路径
}res;
void bfs()
{
queue<node> Q;
node fir,u,v;fir.x=0;fir.y=0;fir.len=0;
Q.push(fir);
while(!Q.empty()){
u=Q.front();
Q.pop();
for(int i=0;i<4;i++){
v.x = u.x + dirx[i];
v.y = u.y + diry[i];
if(v.x<0||v.x>4||v.y<0||v.y>4)
continue;
if(a[v.x][v.y]==0){
a[v.x][v.y]=1;//若可以走,加上这一步的路径,然后入队
v.path[u.len][0]=u.x; v.path[u.len][1]=u.y; v.len=u.len+1;
Q.push(v);
if(v.x==4&&v.y==4){
v.path[v.len][0]=v.x; v.path[v.len][1]=v.y; v.len=v.len+1;
res=v;
return;
}
}
}
}
}
int main(){
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>a[i][j];
bfs();
for(int i=0;i<res.len;i++)
cout<<"("<<res.path[i][0]<<", "<<res.path[i][1]<<")"<<endl;
return 0;
}