POJ3984 迷宫问题【简单搜索】

迷宫问题

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 34530
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
  Accepted: 19645

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)

Source

问题链接POJ3984 迷宫问题

解题思路

bfs

AC的C++代码:

#include<iostream>
#include<queue>
#include<stack>

using namespace std;

int a[5][5];
int path[30];

struct DIR{
	int x,y;
}d[4]={{1,0},{-1,0},{0,1},{0,-1}};

struct Node{
	int x,y;
	Node(){}
	Node(int x,int y):x(x),y(y){}
};

void bfs()
{
	queue<Node>q;
	q.push(Node(0,0));
	a[0][0]=1;
	while(!q.empty()){
		Node e=q.front();
		q.pop();
		if(e.x==4&&e.y==4)
		  return;
		for(int i=0;i<4;i++){
			int x,y;
			x=e.x+d[i].x;
			y=e.y+d[i].y;
			if(0<=x&&x<=4&&0<=y&&y<=4&&!a[x][y]){
				a[x][y]=1;
				int cur=x*5+y;
				int pre=e.x*5+e.y;
				path[cur]=pre;//记录当前结点是由结点e过来的 
				q.push(Node(x,y));
			}
		}
	}
}

int main()
{
	for(int i=0;i<5;i++)
	  for(int j=0;j<5;j++)
	  	scanf("%d",&a[i][j]);
	bfs();
	int t=4*5+4;
	stack<int>s;
	while(t){
		s.push(t);
		t=path[t];
	}
	s.push(0);
	while(!s.empty()){
		int temp=s.top();
		printf("(%d, %d)\n",temp/5,temp%5);
		s.pop();
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/82836023