POJ3894迷宫问题 BFS+stack输出最短路径

本文通过BFS(广度优先搜索)结合栈来解决POJ3894题目中的迷宫问题,详细解析如何找到从起点到终点的最短路径。通过实例和代码解释算法实现过程。
摘要由CSDN通过智能技术生成

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <string>
#include <map>
#include <queue>
#include <stack>
using namespace std;
#define el else

struct P {
	int x, y;
};

int dir[4][2] = { 0,1,1,0,0,-1,-1,0 };
int maze[8][8];
int pre[8][8];      //存入该点回溯的方向,用dir数组,0,2,上下,1,3,左右
bool vis[8][8];
int n;

void bfs(int nx, int ny) {
	queue<P> q;
	P top;
	top.x = nx, top.y = ny;
	q.push(top);
	vis[nx][ny] = 1;
	while (!q.empty()) {
		top = q.front();
		q.pop();
		for (int i = 0; i < 4; ++i) {
			int tx = top.x + dir[i][0];
			int ty = top.y + dir[i][1];
			if (tx == 5 && ty == 5) {
				pre[tx][ty] = (i + 2) % 4;	//记录上一步
				return;
			}
			if (tx > 0 && tx < 6 && ty>0 && ty < 6 && !vis[tx][ty] && maze[tx][ty] == 0) {
				pre[tx][ty] = (i + 2) % 4;	//记录上一步
				vis[tx][ty] = 1;

				P h;    h.x = tx, h.y = ty;
				q.push(h);
			}
		}
	}
}

int main()
{
	for (int i = 1; i <= 5; ++i) {
		for (int j = 1;j <= 5; ++j)
			scanf("%d", &maze[i][j]);
	}
	memset(vis, 0, sizeof(vis));
	memset(pre, 0, sizeof(pre));     //pre一定初始化
	bfs(1, 1);

	int x = 5, y = 5;
	int dx, dy;
	//for (int i = 1; i <= 5; ++i) {
	//	for (int j = 1; j <= 5; ++j) {
	//		printf("%d ", pre[i][j]);
	//	}
	//	puts("");
	//}

	stack<P> s;
	P h;	h.x = 5;	h.y = 5;
	s.push(h);
	while (x != 1 || y != 1) {				//要从终点返回到这查找路径,因为该点上一步唯一,而下一步不唯一。
		dx = dir[pre[x][y]][0];
		dy = dir[pre[x][y]][1];
		h.x = dx + x;	h.y = dy + y;
		s.push(h);                         
		x += dx;
		y += dy;
	}

	while (!s.empty()) {
		printf("(%d, %d)\n", s.top().x-1, s.top().y-1);    
		s.pop();
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值