迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5775 | Accepted: 3317 |
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入门的一道典型题目了。
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
typedef struct
{
int x,y,step;
}sa;
int map[5][5];
int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
bool vis[5][5];
sa pre[5][5];
sa path[30];
bool dis(sa cur)
{
if(cur.x<0||cur.x>4||cur.y<0||cur.y>4)
return false;
return true;
}
void bfs()
{
queue<sa> q;
sa start,now;
start.x=0,start.y=0;
start.step=1;
vis[0][0]=true;
q.push(start);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==4&&now.y==4)break;
for(int c=0;c<4;c++)
{
sa next;
next.x=now.x+dir[c][0];
next.y=now.y+dir[c][1];
next.step=now.step+1;
if(dis(next)&&!map[next.x][next.y]&&!vis[next.x][next.y])
{
pre[next.x][next.y]=now;
vis[next.x][next.y]=true;
q.push(next);
}
}
}
int ans=now.step;
for(int d=ans;d>=0;d--)
{
path[d]=now;
now=pre[now.x][now.y];
}
for(int e=1;e<=ans;e++)
printf("(%d, %d)\n",path[e].x,path[e].y);
}
int main()
{
for(int a=0;a<5;a++)
for(int b=0;b<5;b++)
scanf("%d",&map[a][b]);
bfs();
return 0;
}