如果可以记忆化搜索,切勿写剪枝爆搜
#include<stdio.h>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
#define For(i,a,b) for (int i=a;i<=b;++i)
#define Void inline void
int now,tm,ts[20][20],stp[32768][15],n,m,cap[20][20],tot,ans,inf,dis[20][20];
struct point{int x,y;} pos[15],st;
char s[20][20];
inline bool ins(int x,int y){return 0<x && x<=n && 0<y && y<=m;}
Void K(int x,int y,int del)
{
static const int kx[]={1,1,-1,-1,2,2,-2,-2},ky[]={2,-2,2,-2,1,-1,1,-1};
For(j,0,7) if (ins(x+kx[j],y+ky[j])) cap[x+kx[j]][y+ky[j]]+=del;
}
Void B(int x,int y,int del)
{
static const int kx[]={1,1,-1,-1},ky[]={1,-1,1,-1};
For(j,0,3)
{
int sx=x,sy=y;
while (ins(sx+=kx[j],sy+=ky[j]))
{
cap[sx][sy]+=del;
if (s[sx][sy]!='.') break;
}
}
}
Void R(int x,int y,int del)
{
static const int kx[]={1,0,-1,0},ky[]={0,1,0,-1};
For(j,0,3)
{
int sx=x,sy=y;
while (ins(sx+=kx[j],sy+=ky[j]))
{
cap[sx][sy]+=del;
if (s[sx][sy]!='.') break;
}
}
}
queue<point> Q;
int dfs(int mask,const point &s,int pt)
{
static const int fx[]={1,-1,0,0,1,1,-1,-1},fy[]={0,0,1,-1,1,-1,1,-1};
if (stp[mask][pt]<inf) return stp[mask][pt];
if (mask==(1<<tot)-1) return 0;
ts[s.x][s.y]=++tm;
dis[s.x][s.y]=0;
Q.push(s);
while (!Q.empty())
{
point h=Q.front();Q.pop();
if (::s[h.x][h.y]!='.') continue;
#define X h.x+fx[j]
#define Y h.y+fy[j]
For(j,0,7) if (ins(X,Y) && ts[X][Y]<tm && !cap[X][Y])
Q.push({X,Y}),ts[X][Y]=tm,dis[X][Y]=dis[h.x][h.y]+1;
}
int tmp[tot];
For(i,0,tot-1) tmp[i]=ts[pos[i].x][pos[i].y]==tm?dis[pos[i].x][pos[i].y]:inf;
#define S ::s[pos[i].x][pos[i].y]
For(i,0,tot-1) if (tmp[i]!=inf && S!='.')
{
int tp;
if (S=='K') K(pos[i].x,pos[i].y,-1),tp=1;
if (S=='B') B(pos[i].x,pos[i].y,-1),tp=2;
if (S=='R') R(pos[i].x,pos[i].y,-1),tp=3;
S='.';
stp[mask][pt]=min(stp[mask][pt],tmp[i]+dfs(mask^(1<<i),pos[i],i));
if (tp==1) S='K',K(pos[i].x,pos[i].y,1);
if (tp==2) S='B',B(pos[i].x,pos[i].y,1);
if (tp==3) S='R',R(pos[i].x,pos[i].y,1);
}
return stp[mask][pt];
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
scanf("%d%d",&n,&m);
For(i,1,n) scanf("%s",s[i]+1);
For(i,1,n) For(j,1,m)
{
if (s[i][j]=='*') s[i][j]='.',st={i,j};
if (s[i][j]=='K') K(i,j,1),pos[tot]={i,j},tot++;
if (s[i][j]=='B') B(i,j,1),pos[tot]={i,j},tot++;
if (s[i][j]=='R') R(i,j,1),pos[tot]={i,j},tot++;
}
memset(stp,0x3f,sizeof(stp));
inf=stp[0][0];
ans=dfs(0,st,0);
printf("%d",ans==inf?-1:ans);
}