|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N, M; |
| 7 | + static char[][] map; |
| 8 | + static int[] dx = {-1, 1, 0, 0}; |
| 9 | + static int[] dy = {0, 0, -1, 1}; |
| 10 | + |
| 11 | + public static void main(String[] args) throws IOException { |
| 12 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 14 | + |
| 15 | + N = Integer.parseInt(st.nextToken()); |
| 16 | + M = Integer.parseInt(st.nextToken()); |
| 17 | + |
| 18 | + map = new char[N][M]; |
| 19 | + List<Point> lands = new ArrayList<>(); |
| 20 | + |
| 21 | + for (int i = 0; i < N; i++) { |
| 22 | + String line = br.readLine(); |
| 23 | + for (int j = 0; j < M; j++) { |
| 24 | + map[i][j] = line.charAt(j); |
| 25 | + if (map[i][j] == 'L') { |
| 26 | + lands.add(new Point(i, j)); |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + int maxDistance = 0; |
| 32 | + |
| 33 | + for (Point land : lands) { |
| 34 | + int distance = bfs(land.x, land.y); |
| 35 | + maxDistance = Math.max(maxDistance, distance); |
| 36 | + } |
| 37 | + |
| 38 | + System.out.println(maxDistance); |
| 39 | + } |
| 40 | + |
| 41 | + static int bfs(int startX, int startY) { |
| 42 | + ArrayDeque<Point> queue = new ArrayDeque<>(); |
| 43 | + int[][] distance = new int[N][M]; |
| 44 | + |
| 45 | + for (int i = 0; i < N; i++) { |
| 46 | + Arrays.fill(distance[i], -1); |
| 47 | + } |
| 48 | + |
| 49 | + queue.offer(new Point(startX, startY)); |
| 50 | + distance[startX][startY] = 0; |
| 51 | + |
| 52 | + int maxDist = 0; |
| 53 | + |
| 54 | + while (!queue.isEmpty()) { |
| 55 | + Point current = queue.poll(); |
| 56 | + |
| 57 | + for (int i = 0; i < 4; i++) { |
| 58 | + int nx = current.x + dx[i]; |
| 59 | + int ny = current.y + dy[i]; |
| 60 | + |
| 61 | + if (nx >= 0 && nx < N && ny >= 0 && ny < M) { |
| 62 | + if (map[nx][ny] == 'L' && distance[nx][ny] == -1) { |
| 63 | + distance[nx][ny] = distance[current.x][current.y] + 1; |
| 64 | + maxDist = Math.max(maxDist, distance[nx][ny]); |
| 65 | + queue.offer(new Point(nx, ny)); |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return maxDist; |
| 72 | + } |
| 73 | + |
| 74 | + static class Point { |
| 75 | + int x, y; |
| 76 | + |
| 77 | + Point(int x, int y) { |
| 78 | + this.x = x; |
| 79 | + this.y = y; |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
0 commit comments