#include<bits/stdc++.h>
#define N 55
using namespace std;
struct Node{
int x,y,bs,mas;
string s;
};
operator < (Node a,Node b){
if(a.bs!=b.bs) return a.bs>b.bs;
return a.s>b.s;
}
int dt[N][N];
int fx[4]={0,0,1,-1},fy[4]={1,-1,0,0};
char s[N];
int n,m,k;
vector<vector<set<int> > > bes;
inline bool check(int x,int y,int w){
unsigned now=w,zj=w;
do{
now=(now-1)&w;
if(bes[x][y].find(now)!=bes[x][y].end()) return 1;
}while(now!=w);
return 0;
}
priority_queue<Node> q;
int main(){
scanf("%d%d%d",&n,&m,&k);
int mbx=0,mby=0,sx=0,sy=0;
bes.resize(n);
for(int i=0;i<n;i++) bes[i].resize(m);
for(int i=0;i<n;i++){
scanf("%s",s);
for(int j=0;j<m;j++){
dt[i][j]=s[j]-'a';
if(s[j]=='S'||s[j]=='T') dt[i][j]=-1;
if(s[j]=='T') mbx=i,mby=j;
if(s[j]=='S') sx=i,sy=j;
}
}
q.push((Node){sx,sy,0,0,""});
while(!q.empty()){
Node st=q.top();q.pop();
if(st.x==mbx&&st.y==mby){
for(int i=0;i<st.s.size()-1;i++) cout<<st.s[i];
puts("");
exit(0);
}
st.s.push_back('a');
for(int i=0;i<4;i++){
int tox=st.x+fx[i],toy=st.y+fy[i];
if(tox<0||toy<0||tox==n||toy==m) continue;
int tom=st.mas;
if(dt[tox][toy]!=-1) tom|=(1<<dt[tox][toy]);
if(__builtin_popcount(tom)>k) continue;
st.s[st.s.size()-1]=dt[tox][toy]+'a';
if(check(tox,toy,tom)) continue;
bes[tox][toy].insert(tom);
q.push((Node){tox,toy,st.bs+1,tom,st.s});
}
}
puts("-1");
return 0;
}
codeforces 84E
最新推荐文章于 2019-05-29 13:18:52 发布