优先队列+状压蛇+没有了
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <math.h>
using namespace std;
#include <queue>
#include <stack>
#include <vector>
#include <deque>
#include <set>
#include <map>
#define cler(arr, val) memset(arr, val, sizeof(arr))
#define IN freopen ("in.txt" , "r" , stdin);
#define OUT freopen ("out.txt" , "w" , stdout);
typedef long long LL;
const int MAXN = 5040;//点数的最大值
const int MAXM = 20006;//边数的最大值
const int INF = 0x3f3f3f3f;
const int mod = 10000007;
char mp[102][102];
bool vis[102][102][30];
int n,t;
struct node
{
int x,y,step;
int key;
int she;
bool operator < (const node &a) const
{
return step>a.step;//最小值优先
}
};
priority_queue<node>q;
int xx[4]= {1,0,-1,0};
int yy[4]= {0,1,0,-1};
int star[2],end[2];
bool judge(node p,int dd)
{
if(p.she&(1<<dd))
return false;
return true;
}
int bfs(int x,int y)
{
while(!q.empty())
q.pop();
memset(vis,false,sizeof(vis));
node front,rear;
front.x=x,front.y=y;
front.key=0;
front.step=0;
front.she=0;
vis[x][y][0]=true;
q.push(front);
while(!q.empty())
{
front=q.top();
q.pop();
for(int i=0; i<4; i++)
{
int dx=front.x+xx[i],dy=front.y+yy[i];
if(dx>=0&&dy>=0&&dx<n&&dy<n&&mp[dx][dy]!='#'&&!vis[dx][dy][front.key])
{
if(t==front.key&&mp[dx][dy]=='T')//到终点
{
return front.step+1;
}
else if(mp[dx][dy]==front.key+'0'+1)//拿到钥匙
{
vis[dx][dy][front.key]=true;//标记
rear.key =front.key+1;
rear.x=dx,rear.y=dy,rear.step=front.step+1,rear.she=front.she;
q.push(rear);
}
else if(mp[dx][dy]>=0&&mp[dx][dy]<=5&&judge(front,mp[dx][dy]))//遇到蛇
{
rear.x=dx,rear.y=dy,rear.key=front.key,rear.step=front.step+2,rear.she=(front.she|(1<<mp[dx][dy]));
vis[dx][dy][rear.key]=true;
q.push(rear);
}
else
{
rear.x=dx,rear.y=dy,rear.key=front.key,rear.step=front.step+1,rear.she=front.she;
vis[dx][dy][rear.key]=true;
q.push(rear);
}
}
}
}
return -1;
}
int main()
{
//IN;
while(scanf("%d%d",&n,&t),n+t)
{
for(int i=0; i<n; i++)
scanf("%s",mp[i]);
int ss=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(mp[i][j]=='K')
star[0]=i,star[1]=j;
else if(mp[i][j]=='T')
end[0]=i,end[1]=j;
else if(mp[i][j]=='S')
mp[i][j]=ss++;
}
}
int ans=bfs(star[0],star[1]);
if(ans==-1)
printf("impossible\n");
else printf("%d\n",ans);
}
return 0;
}