K - 迷宫问题
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
一个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 0Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
#include<iostream>
#include<cstdio>
using namespace std;
#define max 5
int arr[max][max];
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
int front,rear;//队首,队尾
struct code{
int x;
int y;
int pre;//用来标记该点的上一个点
} q[100];
void print(int i){//打印最短路径坐标
if(q[i].pre!=-1){
print(q[i].pre);
cout<<"("<<q[i].x<<", "<<q[i].y<<")"<<endl;
}
}
void bfs(int x1,int y1){
int a,b;
q[front].pre=-1;
q[front].x=x1;
q[front].y=y1;
while(front<rear){
for(int i=0;i<4;i++){
a=q[front].x+dx[i];//对队首的周围进行遍历 ,行列坐标发生变化
b=q[front].y+dy[i];
if(a>=5 || a<0 || b<0 || b>=5 || arr[a][b]){//判断盖点是否可以经过
continue;
}
else{
arr[a][b]=1;//标记此点已经走过,不再遍历
q[rear].x=a;//入队
q[rear].y=b;
q[rear].pre=front;
rear++;
}
if(a==4&&b==4){
print(front);
}
}
front++;//队首出队
}
}
int main(){
for(int i=0;i<max;i++)
for(int j=0;j<max;j++){
cin>>arr[i][j];
}
front=0;
rear=1;
cout<<"(0, 0)"<<endl;
bfs(0,0);
cout<<"(4, 4)"<<endl;
return 0;
}