#include <iostream>
#include <queue>
#include <cstring>
#include <algorithm>
#define MAXN 1500
using namespace std;
char map[MAXN][MAXN];
int dist[MAXN][MAXN];
bool visited[MAXN][MAXN];
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
struct node{
int x;
int y;
int min_d;
bool operator < (const node & a) const{
return a.min_d < min_d;
}
};
priority_queue<node> pq;
queue<pair<int,int> > q;
int N,M;
int sx=-1;
int sy,ex,ey;
int bfs(){
while (!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for (int k =0 ; k< 4; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if (nx < 0 || ny < 0 || nx>= N || ny>=M) continue;
if (map[nx][ny]== '.' || dist[nx][ny]!= -1) continue;
dist[nx][ny] = dist[x][y] + 1;
map[nx][ny] = '.';
q.push({nx,ny});
}
}
pq.push({sx,sy,0});
visited[sx][sy] = true;
while (!pq.empty()){
int x = pq.top().x;
int y = pq.top().y;
int min_d = pq.top().min_d;
pq.pop();
if (x == ex && y == ey) return min_d;
for (int k = 0; k< 4; k++){
int nx= x + dx[k];
int ny = y + dy[k];
if (nx < 0 || ny < 0 || nx>= N || ny>=M) continue;
if (visited[nx][ny]) continue;
visited[nx][ny] = true;
pq.push({nx,ny,max(min_d,dist[nx][ny])});
}
}
}
int main(){
scanf("%d%d",&N,&M);
memset(dist,-1,sizeof(dist));
for (int i = 0 ;i < N; i++){
for (int j= 0;j < M; j++){
scanf(" %1c",&map[i][j]);
if (map[i][j] == 'L'){
if (sx == -1) sx = i, sy = j;
else ex = i, ey = j;
map[i][j] = '.';
}
if (map[i][j] == '.'){
q.push({i,j});
dist[i][j] = 0;
}
}
}
cout << bfs() <<"\n";
return 0;
}