【题目大意】:某人a被关在了监狱里,监狱里有路有墙有看守者x,他的朋友们r想去营救他出来,但没前进一个需要消耗时间1,每遇到一个守卫又要花费时间1去杀死他,问最少多少时间可以把a救出来,救不出来输出"Poor ANGEL has to stay in the prison all his life."
【解题思路】:明显的bfs...我才a有很多朋友的地方wa了一次,看题看不仔细啊。T_T!!.......
反过来以a为起点去搜索,找到到所有r所花费的时间即可。
这是一道水题,不过鉴于我这是很少用stl的queue写代码,无聊贴一下吧。
【代码】:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
using namespace std;
#define eps 1e-8
#define pi acos(-1.0)
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long
#define inf 1<<30
struct Tnode{
int x,y,cnt;
Tnode(){}
Tnode(int a,int b,int c){
x=a,y=b,cnt=c;
}
};
int n,m;
char mapp[250][250];
int vis[250][250];
int dis[250][250];
int stx[4]={1,-1,0,0};
int sty[4]={0,0,1,-1};
int x,y,xx,yy,ans;
void solve_bfs(){
queue<Tnode> que;
ans=inf;
memset(vis,0,sizeof(vis));
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
dis[i][j]=inf;
vis[x][y]=1;
que.push(Tnode(x,y,0));
while (!que.empty()){
Tnode p=que.front();
que.pop();
for (int i=0; i<4; i++){
Tnode tmp;
tmp.x=p.x+stx[i];
tmp.y=p.y+sty[i];
tmp.cnt=p.cnt+1;
if (tmp.x>=0 && tmp.x<n && tmp.y>=0 && tmp.y<m && vis[tmp.x][tmp.y]==0 && mapp[tmp.x][tmp.y]!='#' && tmp.cnt<dis[tmp.x][tmp.y]){
if (mapp[tmp.x][tmp.y]=='x') tmp.cnt++;
que.push(tmp);
dis[tmp.x][tmp.y]=tmp.cnt;
vis[tmp.x][tmp.y]=1;
}
}
}
for (int i=0; i<n; i++){
for (int j=0; j<m; j++)
if (mapp[i][j]=='r' && ans>dis[i][j]) ans=dis[i][j];
}
if (ans==inf) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n",ans);
return ;
}
int main() {
while (~scanf("%d%d",&n,&m)){
getchar();
for (int i=0; i<n; i++){
for (int j=0; j<m; j++){
scanf("%c",&mapp[i][j]);
if (mapp[i][j]=='a') {x=i; y=j;}
}
getchar();
}
solve_bfs();
}
return 0;
}
本文介绍了一道经典的广度优先搜索(BFS)算法题目——监狱营救问题。通过从被囚禁者出发寻找最近的朋友位置,利用BFS实现路径搜索与时间计算,最终得出营救所需最短时间。

561

被折叠的 条评论
为什么被折叠?



