本文主要是介绍BFS+优先队列 处理走迷宫类问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对于每组测试数据,在一行内输出找到宝藏所需的最短时间,如果无法找到宝藏,则输出“Game Over!”
输入: 输出:
4 4 2 3 5
ATTE CXE Game Over!
EXTE TXA
ETCE
EXEX
青杨大神出的BFS+优先队列神题, 刚开始看题,一看就知道是以前做过的BFS水题,但是怎么想也想不起来如何处理 每次遇到野怪times+1如何处理;后来看到了prority_queue
还有vis[x][y]不仅仅可以为0或者1还可以记录到达(x,y)点处的最小时间,后果断AC;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define N 59
char map[N][N];
int vis[N][N];
int n,m,tox,toy,beginx,beginy;
int x0[] = {0,0,-1,1};
int y0[] = {1,-1,0,0};
struct Node{
int times,x,y;
Node(){}
Node(int _x,int _y,int _t){
x =_x; y = _y; times = _t;
}
friend bool operator <(Node n1,Node n2){
return n1.times > n2.times;
}
};
priority_queue<Node> q;
void BFS(int &ans) {
while(!q.empty()) q.pop();
q.push(Node(beginx,beginy,0));
map[beginx][beginy] = 'E';
vis[beginx][beginy] = 0;
while(!q.empty()){
Node cur = q.top(); q.pop();
if(cur.x==tox&&cur.y==toy){
ans = cur.times;
return;
}
for(int i = 0;i<4;i++){
Node tem = Node(cur.x+x0[i],cur.y+y0[i],cur.times+1);
if(tem.x>n||tem.x<=0||tem.y<0||tem.y>=n) continue;
if(map[tem.x][tem.y]=='X') continue;
else if(map[tem.x][tem.y]=='E'&&vis[tem.x][tem.y]>tem.times){
vis[tem.x][tem.y] = tem.times;
q.push(tem);
}
else if(map[tem.x][tem.y]=='T'&&vis[tem.x][tem.y]>tem.times+1){
vis[tem.x][tem.y] = tem.times + 1;
tem.times += 1;
q.push(tem);
}
else if(map[tem.x][tem.y]=='A'){
vis[tem.x][tem.y] = tem.times;
q.push(tem);
}
}
}
ans = -1;
}
void init(){
memset(vis,0x0f0f0f0f,sizeof(vis));
}
void getData(){
for(int i = 1;i<=n;i++){
scanf("%s",map[i]);
for(int j = 0;j<m;j++){
if(map[i][j]=='A'){
tox = i;
toy = j;
}
else if(map[i][j]=='C'){
beginx = i;
beginy = j;
}
}
}
}
int main(){
//freopen("Test.txt","r",stdin);
while(~scanf("%d%d",&n,&m)){
init();
getData();
int ans = -1;
BFS(ans);
if(ans==-1) printf("Game Over!\n");
else printf("%d\n",ans);
}
return 0;
}
这篇关于BFS+优先队列 处理走迷宫类问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!