算法提高 学霸的迷宫


经典的BFS问题。刚开始把vis[0][0]状态设置成了1导致dfs溢出。


/*
迷宫bfs求解,SPFA,和迷宫问题考虑用上队列操作
*/
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
#define MAX 505
char map[MAX][MAX];//构造迷宫
int vis[MAX][MAX];//判断点的位置状态
int n, m;
int xx[] = { 1,0,0,-1 };//下上
int yy[] = { 0,1,-1,0 };//右左 
struct node {
	int x;
	int y;//坐标
	int t;//步数 
};
struct father {
	int x;
	int y;//父节点
	char c;//判断上下左右状态 
};
node s, f;//f为末状态
father lj[MAX][MAX];
int bfs() {
	queue<node>Q;
	s.x = 0;
	s.y = 0;
	s.t = 0;
	f.x = n - 1;
	f.y = m - 1;
	lj[s.x][s.y].x = 1000;//节点开始处的前驱设置为无穷大
	lj[s.x][s.y].y = 1000;
	lj[s.x][s.y].y = 0;
	Q.push(s);//s进队列
	while (!Q.empty()) {//队列不为空,循环操作
		node p;
		p = Q.front();
		Q.pop();
		for (int i = 0; i<4; i++) {
			node  pp;
			pp.x = p.x + xx[i];//纵坐标
			pp.y = p.y + yy[i];//横坐标
			pp.t = p.t + 1;
			if (pp.x >= n || pp.x<0 || pp.y >= m || pp.y<0 || vis[pp.x][pp.y] == 1 || map[pp.x][pp.y] == '1') continue;
			Q.push(pp);
			lj[pp.x][pp.y].x = p.x;
			lj[pp.x][pp.y].y = p.y;//连接起来
			if (i == 0) lj[pp.x][pp.y].c = 'D';//下
			else if (i == 1)  lj[pp.x][pp.y].c = 'R';
			else if (i == 2) lj[pp.x][pp.y].c = 'L';
			else if (i == 3) lj[pp.x][pp.y].c = 'U';
			if (pp.x == f.x && pp.y == f.y) return pp.t;
		}
	}
	return -1;
}
void dfs(int x, int y) {
	if (x == 0 && y == 0) return;
	dfs(lj[x][y].x, lj[x][y].y);
	cout << lj[x][y].c;
}
int main(void) {
	int i, j;
	cin >> n >> m;
	for (i = 0; i<n; i++) {
		scanf("%s", map[i]);
	}
	memset(vis, 0, sizeof(vis));
	int ans;
	ans = bfs();
	cout << ans << endl;
	dfs(n - 1, m - 1);//回溯输出方向
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值