POJ 3984--迷宫问题 (BFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/foreverzili/article/details/79843173
迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 29516   Accepted: 16981

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

题目链接

    宽度优先搜索(BFS)按照距开始状态由近及远的顺序进行搜索,因此可以很容易地用来求解最短路径、最少操作之类问题的答案。

AC代码:
#include<cstdio>
#include<utility>
#include<queue>
#include<stack>
using namespace std;
const int INF = 1000;

typedef pair<int, int> P;
int maze[5][5];
// 右 左 下 上 
int dx[] = {0, -1, 1, 0};
int dy[] = {1, 0, 0, -1}; 
P path[5][5];
void bfs(){
for(int i = 0;i < 5; i++)
	for(int j = 0; j < 5; j++){
		path[i][j]= P(INF,INF);
	}
	path[0][0] = P(-1, -1);
	queue<P> Q;
	Q.push(P(0, 0));
	while(!Q.empty()){
		P p = Q.front();
		Q.pop();
		if(p.first == 4 && p.second == 4){
			break;
		}
		// 向四个方向遍历 
		for(int i = 0; i < 4; i++){
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			//若能走且没有走过 
			if(nx>=0 && nx < 5 && ny >=0 && ny < 5 && maze[nx][ny] == 0 && path[nx][ny] == P(INF, INF)){
				
				//存储路径信息(path[nx][ny] 保存它的直接前驱结点) 
				path[nx][ny] = p;
				Q.push(P(nx, ny)); 
			}
		}
	}

}


int main(){
	for(int i = 0; i < 5; i++)
		for(int j = 0; j < 5; j++){
			scanf("%d", &maze[i][j]);
		}
		bfs();
	//用栈保存结果 
	stack<P> ans;
	ans.push(P(4, 4));
	P p = path[4][4];
	while(p != P(-1, -1)){
		ans.push(P(p.first,p.second));
		p = path[p.first][p.second];
		
	}
	//输出结果路径信息 
	while(!ans.empty()){
		printf("(%d, %d)\n",ans.top().first, ans.top().second);
		ans.pop();
		
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/foreverzili/article/details/79843173