題目描述
然而事情並不是Richard想的那麼簡單,等他登陸後他才發現,地圖裏有各種各樣的炸彈和關卡。當Richard經過炸彈的時候,他需要花費1分鐘的時間拆彈;地圖中有關卡對應的通行證,如果Richard拿到了通行證,那麼它就可以通過對應的關卡。現在請你重新爲Richard規劃一條路線,使執行任務的時間最短。
.代表空地
‘#’代表障礙
@代表出發點
*代表任務地點
=代表炸彈
1-4代表通行證
a-d代表關卡
輸入
輸入第一行爲T,即有T組輸入數據(1<=T<=10)
每組數據第一行爲整數N 10≤N≤100,代表地圖的長度和寬度
接下來爲N行,每行N個字符,代表地圖
輸出
輸出一個整數,爲Richard從起點出發到達終點所需的最短時間。
如果Richard無法到達終點,請輸出MISSION FAILED
每組輸出佔一行
樣例輸入
5
@….
.1…
…..
=a###
….*
樣例輸出
8
傳入節點不會段溢出
#include<iostream>
#include<queue>
#include<cstring>
#include <cstdio>
#include<memory.h>
using namespace std;
const int N=120;
int ans, n, treax[10], treay[10], treal;
bool a[N][N][20][64];
int fx[] = {0, 1, 0, -1, 0}, fy[] = {0, 0, 1, 0, -1};
char maze[N][N];
struct node
{
int x, y, time;
int board, trea;
};
int judgenum(int x, int y)
{
for(int i = 1; i <= treal; i++)
{
if(treax[i] == x && treay[i] == y )
{
return i;
}
}
}
node New, now, first;
void bfs(node xxx)
{
queue<node> q;
a[first.x][first.y][first.trea][first.board] = true;
ans = 9999;
q.push(first);
while(!q.empty())
{
now = q.front();
q.pop();
if(maze[now.x][now.y] == '*')
{
ans = min(now.time, ans);
continue;
}
for(int i = 1; i <= 4; i++)
{
New = now;
New.x += fx[i];
New.y += fy[i];
New.time ++ ;
if(New.x < 1 || New.y < 1 || New.x > n || New.y > n || maze[New.x][New.y] == '#')
continue;
char ch = maze[New.x][New.y];
if(ch == '=')
{
int xx = judgenum(New.x, New.y);
if((New.trea & (1<<xx)) == 0)
New.trea |= (1<<xx);
if(!a[New.x][New.y][New.trea][New.board])
{
a[New.x][New.y][New.trea][New.board] = true;
New.time ++;
q.push(New);
}
}
else if(ch >= '1' && ch <= '4')
{
int j = maze[New.x][New.y] - '1';
New.board |= (1<<j);
if(!a[New.x][New.y][New.trea][New.board])
{
q.push(New);
a[New.x][New.y][New.trea][New.board] = true;
}
}
else if(ch >= 'a' && ch <= 'd')
{
if(New.board & (1<<(ch-'a')) && !a[New.x][New.y][New.trea][New.board])
{
a[New.x][New.y][New.trea][New.board] = true;
q.push(New);
}
}
else if(!a[New.x][New.y][New.trea][New.board])
{
a[New.x][New.y][New.trea][New.board] = true;
q.push(New);
}
}
}
}
int main()
{
int t, x, y;
while(scanf("%d", &n) != EOF){
//scanf("%d", &n);
memset(a, 0, sizeof(a));
treal = 0;
for(int i = 1; i <= n; i++)
{
scanf("%s", &maze[i][1]);
for(int j = 1; j <= n; j++)
{
if(maze[i][j] == '@')
{
first.x = i;
first.y = j;
}
else if(maze[i][j] == '=')
{
treax[++treal] = i; treay[treal] = j;
}
}
}
first.time = 0;
first.board = 0;
first.trea = 0;
bfs(first);
if(ans == 9999)
printf("MISSION FAILED\n");
else
printf("%d\n", ans);
}
//}
return 0;
}