J - 迷宫问题 poj 3984 (bfs+输出路径)

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

};

它表示一个迷宫,其中的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<iostream>
#include<cstdio>
using namespace std;
short int next[4][2]={{0,1},{1,0},{-1,0},{0,-1}};
struct Que{
	short int x,y;
	short int f;
}; 

int book[6][6]={0};
int a[6][6];
int pos[6][6]={0};//保存路径
int main()
{
	struct Que que[100];
	short int head=0,tail=0;
	for(int i = 0;i < 5;++i)
	   for(int j = 0;j < 5;++j)
	      cin >> a[i][j];
	que[tail].x = 0;
	que[tail++].y = 0;
	//que[tail++].f = 0;
	while(head < tail)
	{
		struct Que temp = que[head];
		temp.f = head;
		head++;
		int flag = 0;
		for(int k = 0;k < 4;++k)
		{
			short int tx = temp.x+next[0][k];
			short int ty = temp.y+next[1][k];
			if(tx < 0 || tx >= 5 || ty < 0 || ty >= 5)  continue;
			if(!book[tx][ty] && a[tx][ty] == 0)
			{
				que[tail].x = tx;
				que[tail].y = ty;
				que[tail++].f = temp.f;
				book[tx][ty] = 1;
			}
			
			if(tx == 4 && ty == 4)
			  {
			  	  flag = 1;
			  	  break;
			  }
		}
		if(flag)
		   break;
	}
	int t = tail-1;//获取最后节点
	pos[0][0] = 1;
	while(t)   //将路径保存到数组中
	{
		pos[que[t].x][que[t].y] = 1;
		t = que[t].f;
	}
    for(int i = 0;i < 5;++i)
	   for(int j = 0;j < 5;++j) 
	   {
	   	  if(pos[i][j])
	   	     printf("(%d, %d)\n",i,j);
	   }
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40511966/article/details/82941274
今日推荐