本文主要是介绍hdu 1728 逃离迷宫(搜索:BFS+优先队列),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问在给定转弯次数内能不能到达终点
因为限制了转弯次数,所以要想到每次取转弯次数最小的情况
看了网上好多人都是BFS+DFS,找到某一方向后沿着方向一直走
但我是用优先队列解决,每次取出转弯次数最小的情况,当然这样会慢一些
解决第一次转弯不计次数的方法是判断四个方向是否能加入队列,能的话加入即可
代码如下:
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 100
#define LL long long
using namespace std;int m, n;struct Position {int x, y, k, dir;bool operator < (const Position &rhs) const {return k > rhs.k;}
}start, end, cur, tmp;int g[MAXN][MAXN];
bool vis[MAXN][MAXN][12][5];
priority_queue<Position> q;//定义在外面不要忘了清空bool BFS(int k, int x1, int y1, int x2, int y2) {while(!q.empty())q.pop();memset(vis, 0, sizeof(vis));start.x = x1;start.y = y1;start.k = 0;end.x = x2;end.y = y2;end.k = k;cur.k = 0;if(x1-1>=1 && g[x1-1][y1]==0) {//向上cur.x = x1-1;cur.y = y1;cur.dir = 1;q.push(cur);}if(y1-1>=1 && g[x1][y1-1]==0) {//向左cur.x = x1;cur.y = y1-1;cur.dir = 2;q.push(cur);}if(x1+1<=m && g[x1+1][y1]==0) {//向下cur.x = x1+1;cur.y = y1;cur.dir = 4;q.push(cur);}if(y1+1<=n && g[x1][y1+1]==0) {//向右cur.x = x1;cur.y = y1+1;cur.dir = 3;q.push(cur);}while(!q.empty()) {tmp = q.top();q.pop();vis[tmp.x][tmp.y][tmp.k][tmp.dir] = true;if(tmp.x==end.x && tmp.y==end.y) {return true;}if(tmp.x-1>=1 && tmp.dir!=4 && g[tmp.x-1][tmp.y]==0) {//向上cur.x = tmp.x-1;cur.y = tmp.y;cur.dir = 1;cur.k = tmp.k;if(tmp.dir != 1)cur.k++;if(cur.k <= end.k && !vis[cur.x][cur.y][cur.k][cur.dir])q.push(cur);}if(tmp.y-1>=1 && tmp.dir!=3 && g[tmp.x][tmp.y-1]==0) {//向左cur.x = tmp.x;cur.y = tmp.y-1;cur.dir = 2;cur.k = tmp.k;if(tmp.dir != 2)cur.k++;if(cur.k <= end.k && !vis[cur.x][cur.y][cur.k][cur.dir])q.push(cur);}if(tmp.x+1<=m && tmp.dir!=1 && g[tmp.x+1][tmp.y]==0) {//向下cur.x = tmp.x+1;cur.y = tmp.y;cur.dir = 4;cur.k = tmp.k;if(tmp.dir != 4)cur.k++;if(cur.k <= end.k && !vis[cur.x][cur.y][cur.k][cur.dir])q.push(cur);}if(tmp.y+1<=n && tmp.dir!=2 && g[tmp.x][tmp.y+1]==0) {//向右cur.x = tmp.x;cur.y = tmp.y+1;cur.dir = 3;cur.k = tmp.k;if(tmp.dir != 3)cur.k++;if(cur.k <= end.k && !vis[cur.x][cur.y][cur.k][cur.dir])q.push(cur);}}return false;
}int main(void) {int T, k, x1, y1, x2, y2;char ch;scanf("%d", &T);while(T--) {scanf("%d%d", &m, &n);memset(g, 0, sizeof(g));for(int i=1; i<=m; ++i) {getchar();for(int j=1; j<=n; ++j) {ch = getchar();if(ch == '.')g[i][j] = 0;else g[i][j] = -1;}}scanf("%d%d%d%d%d", &k, &y1, &x1, &y2, &x2);if(BFS(k, x1, y1, x2, y2))cout << "yes" << endl;else cout << "no" << endl;}return 0;
}
这篇关于hdu 1728 逃离迷宫(搜索:BFS+优先队列)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!