牛牛走迷宫(bfs最短路)

题目链接
思路:从题意走的步数最小可以知道这道题肯定是求最短路(一般我用bfs),但字典序最小卡住了我,其实要求字典序最小其实我们只需要把每步走的四个方向所代表的字符按字典序最小排列即可,即“DLRU”(先向下,再向左,再向右,最后向上),那么bfs时字典序最小的路径总会在字典序的路径之前,这样所求的最短路便是符合要求的最短路。
ac代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <queue>
using namespace std;
#define int long long
string lll = "DLRU";
int dis[4][2] = { {1,0},{0,-1},{0,1},{-1,0} }; int n, m;
char cnt[505][505];
int vis[505][505];
struct node {
	int x, y; 
	string path;
	node(int _x, int _y, string _path) :x(_x), y(_y), path(_path) {}
};
void bfs(int a, int b) {
	queue<node> k;
	k.push(node(0, 0, ""));
	vis[0][0] = 1;
	while (!k.empty()) {
		node mm = k.front(); k.pop();
		for (int i = 0; i < 4; i++) {
			int c = mm.x + dis[i][0];
			int d = mm.y + dis[i][1];
			if (c >= 0 && c < n && d >= 0 && d < m && !vis[c][d] && cnt[c][d] == '0') {
				vis[c][d] = 1;
				if (c == n - 1 && d == m - 1) {
					string ccc = mm.path; 
					cout << ccc.size()+1 << endl << ccc + lll[i] << endl;
					return;
				}
				string cc = mm.path + lll[i];
				k.push(node(c, d, cc));
			}
		}
	}
	cout << -1 << endl;
	return ;
}
signed main() {
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> cnt[i][j];
	bfs(n, m);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值