HDU 1429--勝利大逃亡(續)【BFS && 狀態壓縮】
勝利大逃亡(續)
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6656 Accepted Submission(s): 2315
Problem Description Ignatius再次被魔王抓走了(搞不懂他咋這麽討魔王喜歡)……
這次魔王汲取了上次的教訓,把Ignatius關在一個n*m的地牢裏,並在地牢的某些地方安裝了帶鎖的門。鑰匙藏在地牢另外的某些地方。剛開始Ignatius被關在(sx,sy)的位置,離開地牢的門在(ex,ey)的位置。Ignatius每分鐘僅僅能從一個坐標走到相鄰四個坐標中的當中一個。
魔王每t分鐘回地牢視察一次。若發現Ignatius不在原位置便把他拎回去。經過若幹次的嘗試,Ignatius已畫出整個地牢的地圖。如今請你幫他計算是否能再次成功逃亡。僅僅要在魔王下次視察之前走到出口就算離開地牢,假設魔王回來的時候剛好走到出口或還未到出口都算逃亡失敗。
Input 每組測試數據的第一行有三個整數n,m,t(2<=n,m<=20,t>0)。接下來的n行m列為地牢的地圖。當中包含:
. 代表路
* 代表墻
@ 代表Ignatius的起始位置
^ 代表地牢的出口
A-J 代表帶鎖的門,相應的鑰匙分別為a-j
a-j 代表鑰匙,相應的門分別為A-J
每組測試數據之間有一個空行。
Output 針對每組測試數據。假設能夠成功逃亡。請輸出須要多少分鐘才幹離開,假設不能則輸出-1。
Sample Input
4 5 17 @A.B. a*.*. *..*^ c..b* 4 5 16 @A.B. a*.*. *..*^ c..b*
Sample Output
16 -1
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> #define maxn 25 using namespace std; int vis[maxn][maxn][1 << 11]; char map[maxn][maxn]; int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; struct node{ int x, y ,step, key; }; int n, m, t, sx, sy; bool check(node a){ if(a.x >= 0 && a.x < n && a.y >= 0 && a.y < m && map[a.x][a.y] != ‘*‘) return true; else return false; } int bfs(){ node now, next; queue<node >q; now.x = sx; now.y = sy; now.step = 0; now.key = 0; vis[now.x][now.y][now.key] = true; q.push(now); while(!q.empty()){ now = q.front(); q.pop(); if(map[now.x][now.y] == ‘^‘ && now.step < t){ return now.step; } if(now.step > t) continue; for(int i = 0; i < 4; ++i){ next.x = now.x + dir[i][0]; next.y = now.y + dir[i][1]; next.step = now.step + 1; if(check(next)){ if(map[next.x][next.y] >= ‘a‘ && map[next.x][next.y] <= ‘z‘){//鑰匙 next.key = now.key | (1 << (map[next.x][next.y] - ‘a‘));//獲得這個鑰匙 if(!vis[next.x][next.y][next.key]){ vis[next.x][next.y][next.key] = 1; q.push(next); } } else if(map[next.x][next.y] >= ‘A‘ && map[next.x][next.y] <= ‘Z‘){//門 next.key = now.key; if(next.key & (1 << (map[next.x][next.y] - ‘A‘))){//擁有這個門的鑰匙 if(!vis[next.x][next.y][next.key]){ vis[next.x][next.y][next.key] = 1; q.push(next); } } } else {//路 next.key = now.key; if(!vis[next.x][next.y][next.key]){ vis[next.x][next.y][next.key] = 1; q.push(next); } } } } } return -1; } int main (){ while(scanf("%d%d%d", &n, &m, &t) != EOF){ memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; ++i){ scanf("%s", map[i]); for(int j = 0; j < m; ++j) if(map[i][j] == [email protected]
HDU 1429--勝利大逃亡(續)【BFS && 狀態壓縮】