Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=1429

BFS + 状态压缩

View Code
 1 #include <cstdio>
2 #include <cctype>
3 #include <queue>
4 using namespace std;
5 const int N=25;
6 const int dx[4]={0,1,0,-1};
7 const int dy[4]={1,0,-1,0};
8 char maze[N][N]={0};
9 int vis[1100][N][N];
10 int n,m,md;
11 struct node
12 {
13 int x,y,key,dis;
14 };
15 queue<node> q;
16 int bfs(int sx,int sy)
17 {
18 while (!q.empty()) q.pop();
19 vis[0][sx][sy]=1;
20 node u={sx,sy,0,0};
21 q.push(u);
22 while (!q.empty())
23 {
24 u=q.front(); q.pop();
25 int x,y,key,dis,nx,ny,nkey,ndis,d;
26 x=u.x; y=u.y; key=u.key; dis=u.dis;
27 if (dis>=md-1) return -1;
28 for (d=0;d<4;d++)
29 {
30 nx=x+dx[d]; ny=y+dy[d]; nkey=key;
31 if (!maze[nx][ny] || maze[nx][ny]=='*') continue;
32 if (isupper(maze[nx][ny]))
33 {
34 int t=maze[nx][ny]-'A';
35 if (!(key&(1<<t))) continue;
36 }
37 if (islower(maze[nx][ny]))
38 {
39 int t=maze[nx][ny]-'a';
40 nkey=key|(1<<t);
41 }
42 if (vis[nkey][nx][ny]) continue;
43 vis[nkey][nx][ny]=1; ndis=dis+1;
44 node v={nx,ny,nkey,ndis};
45 if (maze[v.x][v.y]=='^') return v.dis;
46 q.push(v);
47 }
48 }
49 return -1;
50 }
51 int main()
52 {
53 int i,j,x,y,ans;
54 while (~scanf("%d%d%d",&n,&m,&md))
55 {
56 memset(vis,0,sizeof(vis));
57 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
58 for (i=1;i<=n;i++) for (j=1;j<=m;j++)
59 if (maze[i][j]=='@')
60 {
61 x=i; y=j;
62 maze[i][j]='.';
63 }
64 ans=bfs(x,y);
65 printf("%d\n",ans);
66 }
67 return 0;
68 }

 

posted on 2012-02-17 21:28  Qiuqiqiu  阅读(540)  评论(0编辑  收藏  举报