起初只是用DFS做,但后来发现问题太多了,起点是一个,但可能有多个士兵,要找到最小的距离即要求每一个子问题的结果都是最小值。用深度优先搜索自然不能每次都返回较小值。而广度优先搜索就像使用了分身术一样,4个方向都有friend去找angel,各自返回自己的最小值,所以思路就是BFS+优先队列。
复制代码
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
66
67
68
69
70
71
72
73
74
75
76
77
78<pre name="code" class="cpp"><pre name="code" class="cpp">#include<cstdio> #include<queue> #include<iostream> #include<cstring> using namespace std; char imap[211][211]; int n,m,x_s,y_s,x_e,y_e; struct node { int x,y,step; friend bool operator<(node n1,node n2) // 不能是 bool operator<(node n1,node n2)哦 { return n2.step<n1.step; } }; int dir[4][2]={1,0, -1,0, 0,1, 0,-1}; //不用{{},{}……} int judge(int x,int y) { if(x>=0&&x<n&&y>=0&&y<m&&imap[x][y]!='#')return 1; return 0; } int BFS(){ priority_queue<node>q; node cur,next; int i; cur.x=x_s; cur.y=y_s; cur.step=0; imap[cur.x][cur.y]='#'; q.push(cur); while(!q.empty()) { cur=q.top(); q.pop(); if(cur.x==x_e && cur.y==y_e) return cur.step; //返回最小值 for(i=0;i<4;i++) { next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; if(!judge(next.x,next.y)) continue; if(imap[next.x][next.y]=='x') next.step=cur.step+2; else next.step=cur.step+1; imap[next.x][next.y]='#'; q.push(next); } //cout<<q.top().x<<" "<<q.top().y<<endl; } return -1; } int main() { //freopen("cin.txt","r",stdin); int ans; int i,j; while(~scanf("%d%d",&n,&m)) { memset(imap,0,sizeof(imap)); getchar(); for(i=0;i<n;i++){ for(j=0;j<m;j++){ scanf("%c",&imap[i][j]); if(imap[i][j]=='r'){ x_s=i; y_s=j; } else if(imap[i][j]=='a'){ x_e=i; y_e=j; } } getchar(); } ans=BFS(); if(ans==-1) printf("Poor ANGEL has to stay in the prison all his life.n"); else printf("%dn",ans); } return 0; }
复制代码
1
复制代码
1
最后
以上就是幸福斑马最近收集整理的关于hdu 1242 Rescue(BFS+优先队列)的全部内容,更多相关hdu内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复