迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16315 | Accepted: 9743 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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
题意:基础的BFS题目,在求取最短路径的基础上需要打印路径。
分析:基本的BFS模板,加上一个递归打印路径。在此将5*5迷宫中的每个点编序,其号码为5*x+y,x和y为横纵坐标。建立pre数组记录每个点的前一个点,根据其下标唯一确定那个点,执行递归即可。见AC代码:
#include<stdio.h>
#include<queue>
using namespace std;
const int maxn=6;
int dirx[4]= {0,0,-1,1};
int diry[4]= {-1,1,0,0};
int map[maxn][maxn];
int vis[maxn][maxn];
int sx=0,sy=0,ex=4,ey=4;
struct p
{
int x,y,step,pre;
};
int pre[30];
void Print(int n)
{
// printf("打印\n");
if(n==0)
return ;
Print(pre[n]);
printf("(%d, %d)\n",n/5,n%5);
}
void BFS()
{
queue<p> q;
p p1;
p1.x=sx;
p1.y=sy;
p1.step=0;
pre[0]=-1;
q.push(p1);
while(!q.empty())
{
p f=q.front(),temp;
q.pop();
if(f.x==ex&&f.y==ey)
{
//printf("%d \n",pre[24]);
Print(24);//4 4 转化成24
return ;
}
for(int i=0; i<4; i++)
{
temp.x=f.x+dirx[i];
temp.y=f.y+diry[i];
temp.step=f.step+1;
if(temp.x<=4&&temp.x>=0&&temp.y<=4&&temp.y>=0&&!vis[temp.x][temp.y]&&map[temp.x][temp.y]==0)
{
pre[temp.x*5+temp.y]=f.x*5+f.y;
q.push(temp);
vis[temp.x][temp.y]=1;
}
}
}
}
int main()
{
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
{
scanf("%d",&map[i][j]);
vis[i][j]=0;
}
printf("(0, 0)\n");
BFS();
}
多刷题,长见识。
特记下,以备后日回顾。