#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
#define IOS std::ios::sync_with_stdio(false)
#define pb push_back
#define inf 0x3f3f3f3f
#define YES cout << "YES" << endl;
#define yes cout << "yes" << endl;
#define no cout << "no" << endl;
#define NO cout << "NO" << endl;
#define int long long
#define x first
#define y second
#define cmp [&](PII a, PII b){ return a.y < b.y; }
const int N = 5e5+10, mod = 1e9+7, M = 1e6+5, K = 1e5+10, Z = 2e5+7;
using namespace std;
typedef long long LL;
typedef priority_queue<int> PQI;
typedef priority_queue <int, vector<int>, greater<>> PQGI;
typedef pair<int, int> PII;
bool st[55][55];
char g[55][55];
int n, m;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
vector<PII> a, b;
int get(int x1, int y1, int x2, int y2)
{
return abs(x1 - x2) + abs(y1 - y2);
}
void bfs(int x, int y, int k)
{
queue<PII> q;
if(!k) a.pb({x, y});
else b.pb({x, y});
q.push({x, y});
st[x][y] = true;
while(q.size())
{
PII t = q.front();
q.pop();
int sx = t.first, sy = t.second;
for(int i = 0; i < 4; i ++)
{
int nx = sx + dx[i], ny = sy + dy[i];
if(nx >= 0 && nx <= n && ny >= 0 && ny <= m && g[nx][ny] == 'X' && !st[nx][ny])
{
q.push({nx, ny});
if(!k) a.pb({nx, ny});
else b.pb({nx, ny});
st[nx][ny] = true;
}
}
}
}
void solve()
{
cin >> n >> m;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
cin >> g[i][j];
int t = 0;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
if(g[i][j] == 'X' && !st[i][j])
{
bfs(i, j, t);
t = 1;
}
int res = inf;
for(int i = 0; i < a.size(); i ++)
for(int j = 0; j < b.size(); j ++)
res = min(res, get(a[i].first, a[i].second, b[j].first, b[j].second));
cout << res - 1 << endl;
return;
}
signed main()
{
IOS; cin.tie(nullptr), cout.tie(nullptr);
int T = 1;
// cin >> T;
while( T -- ) solve();
return 0;
}
//这里填你的代码^^
//注意代码要放在两组三个点之间,才可以正确显示代码高亮哦~