代码可能有点乱[汗]
#include<cstdio>
#include<deque>
#include<utility>
#include<cstring>
#include<algorithm>
using namespace std;
const int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int tm[50][50],ttt=1e9,r,c;
pair<int,int>stt,shlt;
bool vsd[50][50];
char mp[50][50];
deque<pair<pair<int,int>,int> >hghg,fld;
int main()
{
memset(tm,0x3f3f3f3f,sizeof(tm));
memset(vsd,false,sizeof(vsd));
scanf("%d%d",&r,&c);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
{
scanf(" %c",&mp[i][j]);
switch(mp[i][j])
{
case '*':fld.push_back(make_pair(make_pair(i,j),0));break;
case 'S':stt=make_pair(i,j);break;
case 'D':shlt=make_pair(i,j);break;
}
}
while(!fld.empty())
{
for(int k=0;k<4;k++)
{
int xk=fld.front().first.first+dx[k],yk=fld.front().first.second+dy[k],tk=fld.front().second+1;
if(xk>0&&xk<r&&yk>0&&yk<c&&mp[xk][yk]=='.'&&!vsd[xk][yk])
{
vsd[xk][yk]=true;
tm[xk][yk]=min(tm[xk][yk],tk);
fld.push_back(make_pair(make_pair(xk,yk),tk));
}
}
fld.pop_front();
}
memset(vsd,false,sizeof(vsd));
hghg.push_back(make_pair(stt,0));
while(!hghg.empty())
{
for(int k=0;k<4;k++)
{
int xk=hghg.front().first.first+dx[k],yk=hghg.front().first.second+dy[k],tk=hghg.front().second+1;
if(make_pair(xk,yk)==shlt)
ttt=min(ttt,tk);
if(xk>0&&xk<r&&yk>0&&yk<c&&mp[xk][yk]=='.'&&!vsd[xk][yk])
{
vsd[xk][yk]=true;
hghg.push_back(make_pair(make_pair(xk,yk),tk));
}
}
hghg.pop_front();
}
if(ttt==1e9)
printf("KAKTUS");
else
printf("%d",ttt);
return 0;
}