POJ3984 迷宫问题【简单BFS+输出路径】

迷宫问题

题意: 在一个5*5的迷宫中,数字0表示为可通过的路,数字1表示为不可通过的墙。问从左上角走到右下角的最短路线,并且输出路径。(题目保证只有一组解,所以不用考虑字典序啥的)

题解: 据说,题目真的只有一组解,你只要复制样例中的输出然后提交就能过。 虽然但是,还是要正儿八经做题的,输出路径最近常干了,甚至自己都已经出过一道输出路径的BFS题目了。添加两个pre数组记录前驱节点的坐标,最后借助栈从终点往起点递推,存入所有经过点,再输出出来即可。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<stack>
using namespace std;

int G[6][6];
int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int pre_x[6][6];
int pre_y[6][6];
struct node{
	int x, y;
	node(){}
	node(int x, int y): x(x), y(y) {}
};

inline bool check(node u) {
	if(u.x < 1 || u.x > 5 || u.y < 1 || u.y > 5)	return false;
	if(G[u.x][u.y] == 1)	return false;
	return true;
}

void print_path() {
	stack<node> St;
	St.push(node(5, 5));
	while(1) {
		node u = St.top();
		node v;
		v.x = pre_x[u.x][u.y];
		v.y = pre_y[u.x][u.y];
		St.push(v);
		if(v.x == 1 && v.y == 1)	break;
	}
	
	while(!St.empty()) {
		node u = St.top(); St.pop();
		printf("(%d, %d)\n", u.x - 1, u.y - 1);
	}
}

void BFS() {
	queue<node> Q;
	Q.push(node(1, 1));
	G[1][1] = 1;
	while(!Q.empty()) {
		node u = Q.front(); Q.pop();
		if(u.x == 5 && u.y == 5) {
			print_path();
			return ;
		}
		for(int i = 0; i < 4; i++) {
			node v = u;
			v.x += dir[i][0], v.y += dir[i][1];
			if(check(v)) {
				pre_x[v.x][v.y] = u.x;
				pre_y[v.x][v.y] = u.y;
				G[v.x][v.y] = 1;
				Q.push(v);
			}
		}
	}
}

int main() {
	ios :: sync_with_stdio(false);	cin.tie(0);	cout.tie(0);
	for(int i = 1; i <= 5; i++) {
		for(int j = 1; j <= 5; j++) {
			cin >> G[i][j];
		}
	}
	
	BFS();
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值