Saving Tang MonkTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 3199 Accepted Submission(s): 1116 Problem Description 《Journey to the West》(also 《Monkey》) is one of the Four Great Classical Novels of Chinese literature. It was written by Wu Cheng'en during the Ming Dynasty. In this novel, Monkey King Sun Wukong, pig Zhu Bajie and Sha Wujing, escorted Tang Monk to India to get sacred Buddhism texts.
Input There are several test cases.
Output For each test case, print the minimum time (in minutes) Sun Wukong needed to save Tang Monk. If it's impossible for Sun Wukong to complete the mission, print "impossible"(no quotes).
Sample Input 3 1 K.S ##1 1#T 3 1 K#T .S# 1#. 3 2 K#T .S. 21. 0 0
Sample Output 5 impossible 8
Source 2014 ACM/ICPC Asia Regional Guangzhou Online
Recommend hujie
|
借鉴:https://blog.youkuaiyun.com/u011721440/article/details/39433547
#include<math.h>
#include<queue>
#include<string.h>
#include <cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 105
#define INF 0X3f3f3f3f
int dir[4][2]={0,1,1,0,0,-1,-1,0};
char g[N][N];
int e[N][N];
int mark[N][N][11];
int n,m,ans;
struct node
{
int x,y,t,id,s; //坐标、时间、钥匙、和杀死的蛇
friend bool operator<(node a,node b)
{
return a.t>b.t;
}
};
int min(int a,int b)
{
return a<b?a:b;
}
bool judge(int x,int y)
{
if(x<0||x>=n||y<0||y>=n||g[x][y]=='#')
return true;
return false;
}
int bfs(int x,int y)
{
int ans=INF;
int i,di,dj;
priority_queue<node>q;
node cur,next;
cur.x=x;cur.y=y;
cur.t=cur.s=0;
cur.id=0;
q.push(cur);
mark[x][y][0]=0;
while(!q.empty())
{
cur=q.top();
q.pop();
if(g[cur.x][cur.y]=='T'&&cur.id==m)
{
ans=min(ans,cur.t);
continue;
}
for(i=0;i<4;i++)
{
next.x=di=cur.x+dir[i][0];
next.y=dj=cur.y+dir[i][1];
next.t=cur.t+1;
next.s=cur.s;
next.id=cur.id;
if(judge(di,dj))
continue;
if(g[di][dj]=='S')
{
int t=e[di][dj];
if((next.s&(1<<t))==0) //杀过的蛇今后就不必在杀
{
next.s|=(1<<t);
next.t++;
}
}
if(next.id==g[di][dj]-'0'-1)
{
next.id++;
}
int t=next.id;
if(mark[di][dj][t]>next.t) //mark来存钥匙的状态,搜索的时候再加个状态
{
mark[di][dj][t]=next.t;
q.push(next);
}
}
return ans;
}
int main()
{
int i,j,k,l,si,sj;
while(scanf("%d%d",&n,&m),n||m)
{
k=0;
memset(e,0,sizeof(e));
for(i=0;i<n;i++)
{
scanf("%s",g[i]);
for(j=0;j<n;j++)
{
if(g[i][j]=='K')
{
si=i;sj=j;
}
if(g[i][j]=='S')
{
e[i][j]=k++; //k只是将每一只蛇区分开。
}
for(l=0;l<10;l++)
{
mark[i][j][l]=INF;
}
}
}
int ans=bfs(si,sj);
if(ans==INF)
printf("impossible\n");
else
printf("%d\n",ans);
}
return 0;
}