您的位置:首页 > 其它

迷宫问题(输出路径)

2016-01-24 20:31 267 查看
迷宫问题


Time Limit:
1000MS Memory
Limit:
65536KB 64bit IO
Format:
%I64d & %I64u

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)


思路:题意很简单,关键是用怎样的方式将路径保存下来,第一次接触这种需要输出路径的题,参考了别人的方法。在结构体中用一个变量来保存当前状态的上一个状态,采用模拟队列来实现出队和入队,用递归的方式来输出途径。

代码如下:

#include"cstdio"
#include"cstring"
#include"iostream"
#include"algorithm"

using namespace std;

int top,rear;
int maze[10][10];
int movex[4] = {1,-1,0,0}; //x前进方式
int movey[4] = {0,0,1,-1}; //y前进方式

struct node
{
int x,y,pre; //pre用来保存当前状态的前一个状态
}node[100];

bool is_block(int x,int y) //判断当前位置能不能走
{
if(x<0 || x>4 || y<0 || y>4)
{
return true;
}
if(maze[x][y])
{
return true;
}
return false;
}

void output(int i) //递归输出走过的坐标
{
if(node[i].pre != -1)
{
output(node[i].pre);
printf("(%d, %d)\n",node[i].x,node[i].y);
}
}

void bfs(int x,int y)
{
node[top].x = x;
node[top].y = y;
node[top].pre = -1;
while(top < rear) //队列不为空
{
for(int i = 0;i < 4;i++)
{
int xx = movex[i]+node[top].x;
int yy = movey[i]+node[top].y;
if(xx == 4 && yy == 4) //走到迷宫的右下角,输出路径
{
output(top);
}
if(is_block(xx,yy))
{
continue;
}
else
{
maze[xx][yy] = 1; //走过的地方变为1(墙壁),相当于标记为已走过
node[rear].x = xx;
node[rear].y = yy;
node[rear].pre = top;
rear++; //入队
}
}
top ++; //出队
}
}

int main()
{
while(~scanf("%d",&maze[0][0]))
{
for(int i = 1;i < 5;i++)
{
scanf("%d",&maze[0][i]);
}
for(int i = 1;i < 5;i++)
{
for(int j = 0;j < 5;j++)
{
scanf("%d",&maze[i][j]);
}
}
top = 0,rear = 1;
puts("(0, 0)");
bfs(0,0);
puts("(4, 4)");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: