HDU1072+BFS

对于状态的处理有点难想。。。

View Code
 1 /*
 2 bfs
 3 */
 4 #include<stdio.h>
 5 #include<string.h>
 6 #include<queue>
 7 #include<stdlib.h>
 8 #include<algorithm>
 9 using namespace std;
10 const int maxn = 12;
11 const int inf = 99999999;
12 int mat[ maxn ][ maxn ];
13 int vis[ maxn ][ maxn ];
14 struct node{
15     int x,y,bomb,t;
16 }s,e;
17 const int dx[] = { 1,-1,0,0 };
18 const int dy[] = { 0,0,1,-1 };
19 
20 void bfs( int n,int m ){
21     int ans = inf;
22     node p,pp;
23     p.x = s.x,p.y = s.y,p.t = 0,p.bomb = 6;
24     vis[ p.x ][ p.y ] = 6;
25     queue<node>q;
26     q.push( p );
27     while( !q.empty() ){
28         p = q.front();
29         q.pop();
30         if( p.x==e.x && p.y==e.y && ans>p.t && p.bomb>0 ){
31             ans = p.t;
32         }
33         for( int i=0;i<4;i++ ){
34             pp.x = p.x+dx[i],pp.y = p.y+dy[i];
35             pp.t = p.t+1,pp.bomb = p.bomb-1;
36             if( pp.x<0||pp.x>=n||pp.y<0||pp.y>=m ) continue;
37             if( mat[ pp.x ][ pp.y ]==0 ) continue;
38             if( pp.bomb>0&&vis[ pp.x ][ pp.y ]<pp.bomb ){
39                 if( mat[ pp.x ][ pp.y ]==4 ){
40                     pp.bomb = 6;
41                 }
42                 vis[ pp.x ][ pp.y ] = pp.bomb;
43                 q.push( pp );
44             }
45         }
46     }
47     if( ans>=inf ) printf("-1\n");
48     else printf("%d\n",ans);
49 }
50 
51 int main(){
52     int n,m;
53     int ca;
54     scanf("%d",&ca);
55     while( ca-- ){
56         scanf("%d%d",&n,&m);
57         for( int i=0;i<n;i++ ){
58             for( int j=0;j<m;j++ ){
59                 scanf("%d",&mat[i][j]);
60                 if( mat[i][j]==2 ) s.x = i,s.y = j;
61                 if( mat[i][j]==3 ) e.x = i,e.y = j;
62                 vis[ i ][ j ] = 0;
63             }
64         }
65         bfs( n,m );
66     }
67     return 0;
68 }
keep moving...
原文地址:https://www.cnblogs.com/xxx0624/p/3041176.html