定义一个二维数组:
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)
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath>
const int maxn=1e5+5;
typedef long long ll;
using namespace std;
int m[10][10],front=0,rear=1;
int mov[5][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct node{
int x,y;
int pre;
}q[55];
void print(int x){//输出
if(q[x].pre !=-1){
print(q[x].pre );//还是要从头开始 ,一遍一遍递归进去
cout<<"("<<q[x].x <<", "<<q[x].y <<")"<<endl;
}
}
void bfs(int ix,int iy){
q[front].x =ix;
q[front].y =iy;
q[front].pre =-1;//第一个点的前一个点是-1
while(front<rear){
for(int i=0;i<4;i++){//四个方向
int fx=q[front].x +mov[i][0];
int fy=q[front].y +mov[i][1];
if(fx<1||fy<0||fx>=5||fy>=5||m[fx][fy])
continue;
else{
m[fx][fy]=1;//标记
q[rear].x =fx;
q[rear].y =fy;
q[rear].pre =front;
rear++;//可以走下去
}
if(fx==4&&fy==4)
print(front);
}//可以走的方向都走过了,进入下一个层
front++;
}
}
int main(){
for(int i=0;i<5;i++){//读入数据
for(int j=0;j<5;j++){
cin>>m[i][j];
}
}
cout<<"(0, 0)"<<endl;
bfs(0,0);//广搜
cout<<"(4, 4)"<<endl;
return 0;
}