hdu 1429 ( 胜利大逃亡(续) )

View Code

   http://acm.hdu.edu.cn/showproblem.php?pid=1429
  1 Problem : 1429 ( 胜利大逃亡(续) )     Judge Status : Accepted
2 状态压缩+BFS
3 用二进制表示第i把钥匙的有无 比如已有第三把和第一把钥匙,则二进制表示为0000000101即整数5,用|添加钥匙
   (如67行),&判断有无某把钥匙(如53行)
4 #include<iostream>
5 #include<stdio.h>
6 #include<string>
7 #include<queue>
8 using namespace std;
9 char map[21][21];
10 int dir[4][2]={1,0,-1,0,0,1,0,-1};
11 int vis[21][21][1028];
12 int n,m,t,ans;
13 struct node
14 {
15 int x,y,dis,key;
16 node(int _x=0,int _y=0,int _dis=0,int _key=0):x(_x),y(_y),dis(_dis),key(_key){};
17 };
18 node s;
19 void BFS()
20 {
21 ans=-1;
22 memset(vis,0,sizeof(vis));
23 vis[s.x][s.y][s.key]=1;
24 queue <node> q;
25 q.push(s);
26 while(!q.empty())
27 {
28 node tt=q.front();
29 q.pop();
30
31 for(int k=0;k<4;k++)
32 {
33 int x=tt.x+dir[k][0];
34 int y=tt.y+dir[k][1];
35 if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]!='*'&&!vis[x][y][tt.key])
36 {
37 if(map[x][y]=='.'||map[x][y]=='@')
38 {
39 vis[x][y][tt.key]=1;
40 q.push(node(x,y,tt.dis+1,tt.key));
41
42 }
43 if(map[x][y]=='^')
44 {
45 if(tt.dis+1<t)ans=tt.dis+1;
46
47 return;
48 }
49 if(map[x][y]>='A'&&map[x][y]<='J')
50 {
51 int key=1<<(map[x][y]-'A');
52 //if((tt.key>>key)&1)
53 if(tt.key&key)
54 {
55 vis[x][y][tt.key]=1;
56 q.push(node(x,y,tt.dis+1,tt.key));
57
58 }
59 }
60 if(map[x][y]>='a'&&map[x][y]<='j')
61 {
62
63 int key=1<<(map[x][y]-'a');
64 if(!vis[x][y][tt.key|key])
65 {
66 vis[x][y][tt.key|key]=1;
67 q.push(node(x,y,tt.dis+1,tt.key|key));
68
69 }
70 }
71 }
72 }
73 }
74 }
75
76 int main()
77 {
78
79 while(scanf("%d%d%d",&n,&m,&t)==3)
80 {
81 for(int i=0;i<n;i++)
82 {
83 scanf("%s",map[i]);
84 for(int j=0;j<m;j++)
85 {
86 if(map[i][j]=='@')
87 {
88 s.x=i;s.y=j;s.dis=0,s.key=0;
89
90 }
91
92 }
93 }
94 BFS();
95 printf("%d\n",ans);
96 }
97 }
posted on 2011-03-24 16:24  4.5.6  阅读(360)  评论(0编辑  收藏  举报