HDU 2822 Dogs【两次bfs】

6 6

..X...

XXX.X.

....X.

X.....

X.....

X.X...

3 5 6 3 

 

如上一个图  告诉起点和终点  X到达不费力气  .到达花费1   问从起点到终点  最少的花费力气

分析:bfs  遇到X在bfs

代码:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 using namespace std;
 6 
 7 const int maxn = 1005;
 8 char s[maxn][maxn];
 9 int vis[maxn][maxn];
10 int n, m;
11 int x0, y0, xn, yn;
12 
13 struct Node {
14     int x, y, id;
15     bool operator<(const Node &n0) const{
16         return id > n0.id;
17     }
18 };
19 priority_queue<Node> q, qq;
20 
21 int xx[4] = { 0, 0, 1, -1 };
22 int yy[4] = { 1, -1, 0, 0 };
23 
24 bool bfs2(Node n0) {
25     while(!qq.empty()) {
26         qq.pop();
27     }
28     qq.push(n0);
29     Node n2;
30     while(!qq.empty()) {
31         Node n1 = qq.top(); qq.pop();
32         if(n1.x == xn && n1.y == yn) return true;
33         for(int i = 0; i < 4; i++) {
34             int tx = n1.x + xx[i];
35             int ty = n1.y + yy[i];
36             if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty] && s[tx][ty] == 'X') {
37                 vis[tx][ty] = vis[n1.x][n1.y];
38                 n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
39                 qq.push(n2);
40                 q.push(n2);
41             }
42         }
43     }
44     return false;
45 }
46     
47 
48 void bfs() {
49     while(!q.empty()) q.pop();
50     memset(vis, 0, sizeof(vis));
51     vis[x0][y0] = 1;
52     Node n0 = (Node) {x0, y0, vis[x0][y0]};
53     q.push(n0);
54     if(s[x0][y0] == 'X') {
55         if(bfs2(n0)) return;
56     }
57     Node n2;
58     while(!q.empty()) {
59         Node n1 = q.top();q.pop();
60         if(n1.x == xn && n1.y == yn) return ;
61         for(int i = 0; i < 4; i++) {
62             int tx = n1.x + xx[i];
63             int ty = n1.y + yy[i];
64             if(tx >= 0 && tx < n && ty >= 0 && ty < m && !vis[tx][ty]) {
65                 if(s[tx][ty] == 'X') {
66                     vis[tx][ty] = vis[n1.x][n1.y];
67                     n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
68                     if(bfs2(n2)) return ;
69                     q.push(n2);
70                 } else {
71                     vis[tx][ty] = vis[n1.x][n1.y] + 1;
72                     n2.x = tx; n2.y = ty; n2.id = vis[tx][ty];
73                     q.push(n2);
74                 }
75             }
76         }
77     }
78 }
79 
80 
81 int main() {
82     while(scanf("%d %d",&n, &m) ) {
83         if(n == 0 && m == 0) break;
84         for(int i = 0; i < n; i++) {
85             scanf("%s",s[i]);
86         }
87         scanf("%d %d %d %d",&x0, &y0, &xn, &yn);
88         x0--; y0--; xn--; yn--;
89         bfs();
90         printf("%d\n", vis[xn][yn] - 1);
91     }
92     return 0;
93 }
View Code

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值