Language: Default 迷宫问题
Description 定义一个二维数组: 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) Source |
#include<stdio.h>
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int a[10][10];//地图
int vis[10][10];//记录是否走过
int go[4][2]= {1,0,-1,0,0,1,0,-1};//四个方向
struct node//记录位置
{
int x,y;
} tmp,tmp2;
queue<node>q;//建立队列
node pre[50][50];//记录前面一个元素
node ans[50];
int bfs()//寻找路径
{
while(!q.empty())//初始化队列
{
q.pop();
}
memset(vis,0,sizeof(vis));//初始化数组
tmp.x=0;//起始点
tmp.y=0;
q.push(tmp);//起始点加入队列
vis[0][0]=1;//标记已经走过
while(!q.empty())//寻找路径
{
tmp=q.front();//拿出首元素
q.pop();//释放空间
for(int i=0; i<4; i++)//寻找下一个点
{
tmp2.x=tmp.x+go[i][0];//记录下一个点得横纵坐标
tmp2.y=tmp.y+go[i][1];
if(tmp2.x>=0&&tmp2.x<=4&&tmp2.y>=0&&tmp2.y<=4&&!vis[tmp2.x][tmp2.y]&&a[tmp2.x][tmp2.y]==0)
{//是否满足题意
vis[tmp2.x][tmp2.y]=vis[tmp.x][tmp.y]+1;//标记已经走过
q.push(tmp2);//放入数组
pre[tmp2.x][tmp2.y].x=tmp.x;//记录他之前的位置
pre[tmp2.x][tmp2.y].y=tmp.y;
}
}
if(vis[4][4])//到终点时结束
break;
}
int lastx=4,lasty=4,x,y;//终点
int num=0;
while(lastx||lasty)//直到循环到起点时
{
ans[num].x=lastx;//记录坐标
ans[num].y=lasty;
num++;//右移一位
x=lastx;
y=lasty;
lastx=pre[x][y].x;//找到前一个点
lasty=pre[x][y].y;
}
printf(“(0, 0)\n”);
for(int i=num-1; i>=0; i–)//输出路径
{
printf(“(%d, %d)\n”,ans[i].x,ans[i].y);
}
}
int main()
{
while(scanf(“%d”,&a[0][0]) != EOF)//输入地图
{
for(int j=1; j<5; j++)
{
scanf(“%d”,&a[0][j]);
}
for(int i=1; i<5; i++)
{
for(int j=0; j<5; j++)
{
scanf(“%d”,&a[i][j]);
}
}
bfs();//寻找路径
}
return 0;
}