fork download
#include <iostream>
#include <queue>
using namespace std;

struct Bird{
	int y, x;
};

struct Compare{
    bool operator()(pair<int, Bird> p1, pair<int, Bird> p2) {
        return p1.first < p2.first;
    }
};

pair<int, int> dir[4] = {
	make_pair(-1, 0), make_pair(1, 0), make_pair(0, -1), make_pair(0, 1)
};
int id = 1;
int R, C;
pair<int, int> dest;
int answer = -1;
char map[1500][1500] = {0,};
bool visited[1500][1500] = {false, };
int melted[1500][1500] = {false, };
int cache[1500][1500] = {false, };
priority_queue<pair<int, Bird>, vector<pair<int, Bird>>, Compare> bq; 

void input(){
	cin>>R>>C;

	for(int i=0;i<R;i++){
		for(int j=0;j<C;j++){
			cin>>map[i][j];
		
			if(map[i][j]!='X') melted[i][j] = true;
			if(map[i][j]=='L'){
				if(id==1){
					Bird b;
					b.y=i;
					b.x=j;
					id=-1;
					bq.push(make_pair(0, b));
					visited[b.y][b.x]=true;
				}else{
					dest=make_pair(i, j);
				}
			}
		}
	}
}

void melting(){
	queue<pair<int, int>> q;
	
	for(int y=0;y<R;y++){
		for(int x=0;x<C;x++){
			if(map[y][x]=='X') continue;
			for(int i=0;i<4;i++){
				int ny = y+dir[i].first;
				int nx = x+dir[i].second;
				
				if(melted[ny][nx]) continue;
				if(ny<0||ny>=R||nx<0||nx>=C) continue;
				if(map[ny][nx]=='X'){
					melted[ny][nx] = true;
					cache[ny][nx] = cache[y][x] + 1;
					q.push(make_pair(ny, nx));
				} 
			}
		}
	}
	
	while(!q.empty()){
		int y = q.front().first;
		int x = q.front().second;
		q.pop();
		
		for(int i=0;i<4;i++){
			int ny = y+dir[i].first;
			int nx = x+dir[i].second;
			if(ny<0||ny>=R||nx<0||nx>=C) continue;
			if(!melted[ny][nx]){
				melted[ny][nx] = true;
				cache[ny][nx] = cache[y][x] + 1;
				q.push(make_pair(ny, nx));
			}
		}
	}
}

void moveTheBirds(){
	while(!bq.empty()){
		Bird b = bq.top().second;
		answer = max(-bq.top().first, answer);
		bq.pop();
		// cout<<b.y<<" "<<b.x<<'\n';
		if(b.y==dest.first && b.x==dest.second){
			cout<<answer<<'\n';
			return;
		}
		
		for(int i=0;i<4;i++){
			int ny = b.y+dir[i].first;
			int nx = b.x+dir[i].second;
			if(ny<0||ny>=R||nx<0||nx>=C) continue;
			if(visited[ny][nx]) continue;
			visited[ny][nx] = true;
			Bird nb;
			nb.y=ny;
			nb.x=nx;
			bq.push(make_pair(-cache[ny][nx], nb));
		}
	}
}

int main() {
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(0);
	
	input();
	melting();
	moveTheBirds();

	return 0;
}
Success #stdin #stdout 0.01s 9764KB
stdin
8 17
...XXXXXX..XX.XXX
....XXXXXXXXX.XXX
...XXXXXXXXXXXX..
..XXXXX.LXXXXXX..
.XXXXXX..XXXXXX..
XXXXXXX...XXXX...
..XXXXX...XXX....
....XXXXX.XXXL...
stdout
2