4 5 17 @A.B. a*.*. *..*^ c..b* 4 5 16 @A.B. a*.*. *..*^ c..b*
16 -1每个位置都有不同钥匙的状态经过。#include<stdio.h> #include<iostream> #include<string.h> #include<queue> using namespace std; typedef struct nnn { int t,key,x,y; }NODE; int Key[25][25][1<<10],T,n,m; char map[25][25]; int abs(int x) { return x>=0?x:-x; } int bfs(int sx,int sy) { queue<NODE>q; NODE now,pre; int dir[4][2]={0,1,0,-1,1,0,-1,0}; int tx,ty; now.key=0; now.t=0; now.x=sx; now.y=sy; Key[sy][sx][0]=1; q.push(now); while(!q.empty()) { pre=q.front(); q.pop(); for(int i=0; i<4; i++) { now=pre; ty=pre.y+dir[i][0]; tx=pre.x+dir[i][1]; if(ty>=0&&ty<n&&tx>=0&&tx<m&&pre.t<T-1&&map[ty][tx]!=‘*‘) { now.t++; now.y=ty; now.x=tx; if(map[ty][tx]==‘^‘) return now.t; if(map[ty][tx]>=‘a‘&&map[ty][tx]<=‘j‘){ now.key|=(1<<(map[ty][tx]-‘a‘)); if(Key[ty][tx][now.key]==0) Key[ty][tx][now.key]=1,q.push(now); } else if(map[ty][tx]>=‘A‘&&map[ty][tx]<=‘J‘) { if(Key[ty][tx][now.key]==0&&(pre.key&(1<<(map[ty][tx]-‘A‘)))) Key[ty][tx][now.key]=1, q.push(now); } else if(Key[ty][tx][now.key]==0){ Key[ty][tx][now.key]=1; q.push(now); } } } } return -1; } int main() { int sx,sy,ex,ey; while(scanf("%d%d%d",&n,&m,&T)>0) { for(int i=0; i<n; i++) scanf("%s",map[i]); for(int y=0 ; y<n; y++) for(int x=0 ; x<m; x++) if(map[y][x]==‘@‘) sy=y,sx=x; else if(map[y][x]==‘^‘) ey=y,ex=x; if(abs(sy-ey)+abs(sx-ex)>=T) { printf("-1\n"); continue; } memset(Key,0,sizeof(Key)); printf("%d\n",bfs(sx,sy)); } }
hdu1429胜利大逃亡(续) (状态压缩+BFS),布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010372095/article/details/25082525