|
| 1 | +package graph; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.LinkedList; |
| 7 | +import java.util.Queue; |
| 8 | +import java.util.StringTokenizer; |
| 9 | + |
| 10 | +/** |
| 11 | + * [조건] |
| 12 | + * 육지(L), 바다(W) |
| 13 | + * 인접 상하좌우의 육지로만 이동 가능 |
| 14 | + * 보물은 서로 간에 최단 거리로 이동하는 데 있어 가장 긴 시간이 걸리는 육지 두 곳에 나뉘어 묻혀있다 |
| 15 | + * |
| 16 | + * 지도가 주어질 때, 보물이 묻혀 있는 두 곳간의최단 거리로 이동하는 시간을 구하라 |
| 17 | + * |
| 18 | + * [풀이] |
| 19 | + * 모든 육지인 칸에 대해서 탐색하며 |
| 20 | + */ |
| 21 | +public class BOJ_2589_보물섬 { |
| 22 | + |
| 23 | + static int N, M; |
| 24 | + static char[][] map; |
| 25 | + static int[] di = {-1, 1, 0, 0}; |
| 26 | + static int[] dj = {0, 0, -1, 1}; |
| 27 | + static int result = 0; |
| 28 | + |
| 29 | + public static void main(String[] args) throws IOException { |
| 30 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 31 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 32 | + |
| 33 | + N = Integer.parseInt(st.nextToken()); |
| 34 | + M = Integer.parseInt(st.nextToken()); |
| 35 | + |
| 36 | + map = new char[N][M]; |
| 37 | + for (int i = 0; i < N; i++) { |
| 38 | + String str = br.readLine(); |
| 39 | + for (int j = 0; j < M; j++) { |
| 40 | + map[i][j] = str.charAt(j); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + solution(); |
| 45 | + System.out.println(result); |
| 46 | + } |
| 47 | + |
| 48 | + static void solution() { |
| 49 | + for (int i = 0; i < N; i++) { |
| 50 | + for (int j = 0; j < M; j++) { |
| 51 | + if (map[i][j] == 'L') { // 육지 |
| 52 | + bfs(i, j); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + static void bfs(int startI, int startJ) { |
| 59 | + int max = 0; |
| 60 | + |
| 61 | + Queue<int[]> que = new LinkedList<>(); |
| 62 | + int[][] visited = new int[N][M]; |
| 63 | + |
| 64 | + que.add(new int[]{startI, startJ}); |
| 65 | + visited[startI][startJ] = 1; // 방문하지 않은 곳과의 구분을 위해 0이 아닌 1로 초기화 |
| 66 | + |
| 67 | + while (!que.isEmpty()) { |
| 68 | + int[] cur = que.poll(); |
| 69 | + int i = cur[0], j = cur[1]; |
| 70 | + |
| 71 | + for (int d = 0; d < 4; d++) { |
| 72 | + int nextI = i + di[d]; |
| 73 | + int nextJ = j + dj[d]; |
| 74 | + |
| 75 | + if (nextI < 0 || nextJ < 0 || nextI > N-1 || nextJ > M-1) continue; |
| 76 | + if (map[nextI][nextJ] != 'L') continue; |
| 77 | + if (visited[nextI][nextJ] != 0) continue; |
| 78 | + |
| 79 | + visited[nextI][nextJ] = visited[i][j] + 1; |
| 80 | + que.add(new int[]{nextI, nextJ}); |
| 81 | + |
| 82 | + max = Math.max(max, visited[nextI][nextJ]); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + // 최댓값 갱신 |
| 87 | + result = Math.max(result, max-1); |
| 88 | + } |
| 89 | + |
| 90 | +} |
0 commit comments