迷宫问题 POJ - 3984

1 篇文章 0 订阅

题目

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 20975 Accepted: 12281

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经典应用题。。。

代码

#include <iostream>
#include <stack>
#include <queue>
#include <utility>
#include <cstring>

using namespace std;
typedef pair<int, int > P;
#define MAX_N 6
P G, S;
int dx[] = {-1, 0, 0, 1};
int dy[] = { 0, 1,-1, 0};
int maze[MAX_N][MAX_N];
P parents[MAX_N][MAX_N];
bool used[MAX_N][MAX_N];
int NX, NY;
void bfs();
void solve();

int main()
{
    NX = NY = 4;
    S = P(0, 0); G = P(4, 4);
    for (int i = 0; i <= NX; i++) {
		for (int j = 0; j <= NY; j++) {
			cin >> maze[i][j];
		}
    }
    solve();
    return 0;
}

void bfs() {
	queue<P> que;
	memset(parents, -1, sizeof(parents));
	memset(used, false, sizeof(used));
	que.push(make_pair(S.first, S.second) );
	used[S.first][S.second] = true;

	while (!que.empty()) {
		P v = que.front(); que.pop();
		if (v == G) break;
		for (int i = 0; i < 4; i++) {
			int nx = v.first + dx[i],  ny = v.second + dy[i];
			if (nx >= 0 && nx <= NX && ny >= 0 && ny <= NY && !used[nx][ny] && maze[nx][ny] == 0) {
				que.push(make_pair(nx, ny) );
				parents[nx][ny] = v;
				used[nx][ny] = true;
			}
		}
	}
}

void solve() {
	bfs();
//	cout << "parents: " << endl;
//	for (int i = 0; i <= 4; i++) {
//		for (int j = 0; j <= 4; j++) {
//			cout.width(2);
//			cout << "(" << parents[i][j].first << ",";
//			cout.width(2);
//			cout << parents[i][j].second << ") " << " ";
//		}
//		cout << endl;
//	}
	P v = G;
	stack<P> path;
	path.push(v);
	int nx = v.first, ny = v.second;
	while(parents[v.first][v.second] != P(-1,-1)) {
		path.push(parents[v.first][v.second]);
		v = parents[v.first][v.second];
	}
	while (!path.empty()) {
		P vs = path.top();  path.pop();
		cout << "(" << vs.first << ", " << vs.second << ")" << endl;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值