### 代码

//奶牛选美，Flood Fill算法+曼哈顿距离，BFS
#include<bits/stdc++.h>

using namespace std;

typedef pair<int,int> PII;

const int N = 55;

int n, m;
char g[N][N];
bool st[N][N];

void bfs(int x, int y, vector<PII> &points)
{
queue<PII> q;
q.push({x, y});
st[x][y] = true;

int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};

while(q.size())
{
auto t = q.front();q.pop();
points.push_back(t);

for(int i = 0; i < 4; i++)
{
int a = t.first + dx[i], b = t.second + dy[i];

if(a < 0 || a >= n || b < 0 || b >= m) continue;
if(g[a][b] == '.') continue;
if(st[a][b]) continue;

q.push({a, b});
st[a][b] = true;
}
}
}

int main()
{
cin >> n >> m;

for(int i = 0; i < n; i++) cin >> g[i];

vector<PII> points[2];

for(int i = 0, k = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(g[i][j] == 'X' && !st[i][j])
{
bfs(i, j, points[k++]);
}
}
}

int res = 1e8;
for(auto &x : points[0])
for(auto &y : points[1])
res = min(res, abs(x.first - y.first) + abs(x.second - y.second));
cout << res  - 1 << endl;

return 0;
}

//Flood Fill 算法+ 曼哈顿距离 DFS
#include<bits/stdc++.h>

using namespace std;

typedef pair<int,int> PII;

const int N = 55;

int n, m;
char g[N][N];
bool st[N][N];

void dfs(int x, int y, vector<PII> &points)
{
st[x][y] = true;
points.push_back({x,y});

int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};

for(int i = 0; i < 4; i++)
{
int a = x + dx[i], b = y + dy[i];

if(a < 0 || a >= n || b < 0 || b >= m) continue;
if(g[a][b] == '.') continue;
if(st[a][b]) continue;

dfs(a, b, points);
}
}

int main()
{
cin >> n >> m;

for(int i = 0; i < n; i++) cin >> g[i];

vector<PII> points[2];

for(int i = 0, k = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(g[i][j] == 'X' && !st[i][j])
{
dfs(i, j, points[k++]);
}
}
}

int res = 1e8;
for(auto &x : points[0])
for(auto &y : points[1])
res = min(res, abs(x.first - y.first) + abs(x.second - y.second));
cout << res  - 1 << endl;

return 0;
}