迷宫问题
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 37977 Accepted: 21300
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)
问题描述
很基本的迷宫问题
问题分析
BFS可以找到最快的方式。用visited记录经历过的状态。用string记录路径。
c++程序如下
#include<iostream>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
bool visited[6][6];
int maze[6][6];
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
string ss;
struct state
{
int x,y;
string road;
}q,p;
void bfs();
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&maze[i][j]);
}
}
bfs();
int len=ss.size();
for(i=0;i<len;i+=2)
{
printf("(%c, %c)\n",ss[i],ss[i+1]);
}
return 0;
}
void bfs()
{
memset(visited,0,sizeof(visited));
q.x=0,q.y=0;
q.road="00";
queue<state>Q;
Q.push(q);
visited[1][1]=1;
while(!Q.empty())
{
q=Q.front();
Q.pop();
if(q.x==4&&q.y==4)
{
ss=q.road;
while(!Q.empty()) Q.pop();
return;
}
int i;
for(i=0;i<4;i++)
{
p=q;
p.x+=dir[i][0];
p.y+=dir[i][1];
if(!visited[p.y][p.x]&&p.y>=0&&p.y<=4&&p.x>=0&&p.x<=4&&maze[p.y][p.x]==0)
{
visited[p.y][p.x]=1;
p.road+='0'+p.y;
p.road+='0'+p.x;
Q.push(p);
}
}
}
}