import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static class Pos {
int r;
int c;
int cost;
public Pos(int r, int c, int cost) {
super();
this.r = r;
this.c = c;
this.cost = cost;
}
}
static int[] dr = { -1, 1, 0, 0 };
static int[] dc = { 0, 0, -1, 1 };
static int N, M, max;
static char[][] map;
static boolean[][] used;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
max = Integer.MIN_VALUE;
map = new char[N][M];
for (int i = 0; i < N; i++) {
String s = br.readLine();
for (int j = 0; j < M; j++) {
map[i][j] = s.charAt(j);
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 'L') {
used = new boolean[N][M];
used[i][j] = true;
bfs(new Pos(i, j, 0));
}
}
}
System.out.println(max);
}
private static void bfs(Pos start) {
Queue<Pos> q = new LinkedList<>();
q.add(start);
while (!q.isEmpty()) {
Pos now = q.poll();
int r = now.r;
int c = now.c;
int cost = now.cost;
max = Math.max(max, cost);
for (int i = 0; i < 4; i++) {
int nr = r + dr[i];
int nc = c + dc[i];
if (nr < 0 || nc < 0 || nr >= N || nc >= M) continue;
if (used[nr][nc] || map[nr][nc] == 'W') continue;
used[nr][nc] = true;
q.add(new Pos(nr, nc, cost+1));
}
}
}
}
모든 육지에서 BFS 를 수행한다
라는 접근을 하면 쉽게 해결이 가능함Pos
클래스의 멤버변수로 cost
를 추가L
을 찾을 때마다 BFS 를 수행하며, 수행 시 마다 방문 배열을 초기화하고 수행