#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=1000;
const int maxm=100000;
const int INF=0x3f3f3f3f;
struct Edge {
int to,next,cap,cost;
Edge(){}
Edge(int to,int next,int cap,int cost):to(to),next(next),cap(cap),cost(cost){}
}edge[maxm];
int first[maxn],tot;
int pre[maxn],dis[maxn];
bool vis[maxn];
int N; //节点总个数,节点编号从0~N-1
void init(int n){
N=n;
tot=0;
memset(first,-1,sizeof(first));
}
void addedge(int u,int v,int cap,int cost){
edge[tot]=Edge(v,first[u],cap,cost);
first[u]=tot++;
edge[tot]=Edge(u,first[v],0,-cost);
first[v]=tot++;
}
bool spfa(int s,int t){
queue<int>q;
for(int i=0;i<N;i++) {
dis[i]=INF;
vis[i]=false;
pre[i]=-1;
}
dis[s]=0;
vis[s]=true;
q.push(s);
while(!q.empty()) {
int u=q.front();
q.pop();
vis[u]=false;
for(int i= first[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(edge[i].cap&&dis[v]>dis[u]+edge[i].cost ){
dis[v]=dis[u]+edge[i].cost;
pre[v]=i;
if(!vis[v]) {
vis[v]=true;
q.push(v);
}
}
}
}
if(pre[t]==-1) return false;
else return true;
}
int minCostMaxflow(int s,int t,int &cost) {
int flow=0;
cost = 0;
while(spfa(s,t)) {
int Min=INF;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){
if(Min >edge[i].cap)Min=edge[i].cap;
}
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){
edge[i].cap-=Min;
edge[i^1].cap+=Min;
cost+=edge[i].cost*Min;
}
flow+=Min;
}
return flow;
}
int a[maxn][2],b[maxn][2];
int tot1,tot2;
int main(){
int n,m,i,j;
while(scanf("%d%d",&n,&m)!=EOF){
if(!n&&!m)break;
tot=0;
memset(first,-1,sizeof(first));
tot1=tot2=0;
char s[150];
for(i=0;i<n;i++){
scanf("%s",s);
for(j=0;j<m;j++){
if(s[j]=='m'){
tot1++;
a[tot1][0]=i;
a[tot1][1]=j;
}
if(s[j]=='H'){
tot2++;
b[tot2][0]=i;
b[tot2][1]=j;
}
}
}
N=tot1*2+2;
for(i=1;i<=tot1;i++){
for(j=1;j<=tot2;j++){
addedge(i,j+tot1,1,abs(a[i][0]-b[j][0])+abs(a[i][1]-b[j][1]));
}
}
for(i=1;i<=tot1;i++){
addedge(0,i,1,0);
}
for(i=1;i<=tot2;i++){
addedge(i+tot1,tot1+tot2+1,1,0);
}
int cost;
minCostMaxflow(0,tot1+tot2+1,cost);
printf("%d\n",cost);
}
return 0;
}