我是靠谱客的博主 虚幻未来,这篇文章主要介绍ZOJ1649 营救Rescue (BFS),现在分享给大家,希望可以做个参考。

题目链接

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1649

题意

Angel被抓了,并且被关在监狱里。监狱可以用一个NxM的矩阵来表示。监狱由NxM个方格表示,每个方格可能为墙壁、道路、警卫、她的朋友和她。angel的朋友可以向上、下、左、右四个方向走,走到为道路的方格需要时间1,走到有警卫的方格需要时间2(杀死警卫需要时间1)。从r到a至少需要多少时间?

题解

注意到题干是friends,所以r可能有多个,也就是说应该从a广搜到r。
用一个优先队列来实现广搜,将用时最少的放在队首。即用一个结构体node来存放a到达某个方格的状态。该结构体包含方格里的值,到该方格的时间,方格的坐标。

代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <cstdio> #include <cstring> #include <queue> using namespace std; const int maxn=4e4+100; struct node { char v; int t,x,y; }a[maxn]; char map[220][220]; int N,M,dir[4][2]={0,1,0,-1,1,0,-1,0},vis[220][220]; priority_queue<node> que; bool operator<(const node &n1,const node &n2) { return n1.t>n2.t; } bool valid(int x,int y) { return map[x][y]!='#' && x<=N&&x>=1 && y<=M&&y>=1 && !vis[x][y]; } void bfs() { while(!que.empty()) { que.pop(); } for(int i=1;i<=N;i++) for(int j=1;j<=M;j++) if(map[i][j]=='a') que.push(node{'a',0,i,j}),vis[i][j]=1; while(!que.empty()) { node tmp=que.top();que.pop(); if(tmp.v=='r') { printf("%dn",tmp.t); return; } for(int i=0;i<4;i++) { int fx=tmp.x+dir[i][0]; int fy=tmp.y+dir[i][1]; if(valid(fx,fy)) { vis[fx][fy]=1; node now={map[fx][fy],tmp.t+1,fx,fy}; now.t=map[fx][fy]=='x'?now.t+1:now.t; que.push(now); } } } printf("Poor ANGEL has to stay in the prison all his life.n"); } int main() { while(~scanf("%d%d",&N,&M)) { memset(vis,0,sizeof(vis)); for(int i=1;i<=N;i++) scanf("%s",map[i]+1); bfs(); } return 0; }

最后

以上就是虚幻未来最近收集整理的关于ZOJ1649 营救Rescue (BFS)的全部内容,更多相关ZOJ1649内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部