#include <bits/stdc++.h> //Created by CUBERLONG
using namespace std; //Created by CUBERLONG
#define int long long
void _time() {
#ifndef ONLINE_JUDGE
cout << "_nTime: " << (int)clock() << "ms.n"; //Created by CUBERLONG
#endif
}
void fast() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("ab.inp", "r", stdin);
freopen("ab.out", "w", stdout);
#endif
}
#define II pair<int,int>
#define x first
#define y second
const int N = 1505;
int r, c;
int f[N][N];
char a[N][N];
bool visited[N][N];
II dxy[] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
vector<II> L;
queue<II> qu1, qu2;
bool inside(II x) {
return 0 <= x.x && x.x < r && 0 <= x.y && x.y < c;
}
void visit(II u, int len, bool next) {
len += next;
for (II d: dxy) {
II v = {u.x + d.x, u.y + d.y};
if (inside(v) && !visited[v.x][v.y] && f[v.x][v.y] <= len) {
visited[v.x][v.y] = 1;
qu1.push(v);
}
}
}
int bfs() {
qu1.push(L[0]);
visited[L[0].x][L[0].y] = 1;
for (int len = 0; 1; ++len) {
while (!qu1.empty()) {
II u = qu1.front(); qu1.pop();
qu2.push(u);
visit(u, len, 0);
}
while (!qu2.empty()) {
II u = qu2.front(); qu2.pop();
if (u == L[1]) return len;
visit(u, len, 1);
}
}
return -1;
}
signed main() {
fast();
cin >> r >> c;
memset(f, -1, sizeof f);
queue<II> qu;
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
cin >> a[i][j];
if (a[i][j] == 'L')
L.push_back({i, j});
if (a[i][j] != 'X') {
f[i][j] = 0;
qu.push({i, j});
}
}
while (!qu.empty()) {
II u = qu.front(); qu.pop();
for (II d: dxy) {
II v = {u.x + d.x, u.y + d.y};
if (inside(v) && f[v.x][v.y] < 0) {
f[v.x][v.y] = f[u.x][u.y] + 1;
qu.push(v);
}
}
}
cout << bfs();
return _time(), 0;
} //Created by CUBERLONG
/*
*/
{"html5":"htmlmixed","css":"css","javascript":"javascript","php":"php","python":"python","ruby":"ruby","lua":"text\/x-lua","bash":"text\/x-sh","go":"go","c":"text\/x-csrc","cpp":"text\/x-c++src","diff":"diff","latex":"stex","sql":"sql","xml":"xml","apl":"apl","asterisk":"asterisk","c_loadrunner":"text\/x-csrc","c_mac":"text\/x-csrc","coffeescript":"text\/x-coffeescript","csharp":"text\/x-csharp","d":"d","ecmascript":"javascript","erlang":"erlang","groovy":"text\/x-groovy","haskell":"text\/x-haskell","haxe":"text\/x-haxe","html4strict":"htmlmixed","java":"text\/x-java","java5":"text\/x-java","jquery":"javascript","mirc":"mirc","mysql":"sql","ocaml":"text\/x-ocaml","pascal":"text\/x-pascal","perl":"perl","perl6":"perl","plsql":"sql","properties":"text\/x-properties","q":"text\/x-q","scala":"scala","scheme":"text\/x-scheme","tcl":"text\/x-tcl","vb":"text\/x-vb","verilog":"text\/x-verilog","yaml":"text\/x-yaml","z80":"text\/x-z80"}