代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=100+5;
char mpt[maxn][maxn];
int vis[maxn][maxn][4];
int dir[4][2]={
{
0,1},{
1,0},{
0,-1},{
-1,0}};//右下左上四个方向
struct node{
int x,y;
};
#define inf 0x3f3f3f3f
int n,m;
node p[4];
void bfs(int index)
{
queue<node>q;
node now;
now.x=p[index].x;
now.y=p[index].y;
q.push(now);
vis[now.x][now.y][index]=0;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<4;++i)
{
int nx=now.x+dir[i][0];
int ny=now.y+dir[i][1];
if(nx<1||nx>n||ny<1||ny>m) continue;
int tmp=vis[now.x][now.y][index];
if(mpt[nx][ny]=='#') tmp++;
if(tmp<vis[nx][ny][index])
{
vis[nx][ny][index]=tmp;
q.push(node{
nx,ny});
}
}
}
}
int main()
{
while(cin>>n>>m)
{
memset(vis,inf,sizeof(vis));
memset(mpt,'0',sizeof(mpt));
for(int i=1;i<=n;++i)
{
scanf("%s",mpt[i]+1);
for(int j=1;j<=m;++j)
{
if(mpt[i][j]=='w')
{
p[1].x=i;
p[1].y=j;
}
if(mpt[i][j]=='W')
{
p[2].x=i;
p[2].y=j;
}
if(mpt[i][j]=='f')
{
p[3].x=i;
p[3].y=j;
}
}
}
bfs(1);
bfs(2);
bfs(3);
int ans=inf;
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
int tmp=0;
for(int k=1;k<=3;++k)
{
tmp+=vis[i][j][k];
}
if(mpt[i][j]=='#')
{
tmp-=2;
}
ans=ans<tmp?ans:tmp;
}
}
cout<<ans<<endl;
}
return 0;
}