Home [BOJ 2468] 안전 영역
Post
Cancel

[BOJ 2468] 안전 영역

안전 영역 (2468번)

https://www.acmicpc.net/problem/2468

풀이방법

  • 1~100까지 물의 높이가 될 수 있지만 입력값의 최대값을 최대 가능한 물의 높이로 생각한다.
  • 0부터 최대값까지 반복하면서 map의 (0, 0)부터 bfs로 탐색한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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 int n = 0;
    static int[][] map = null;
    static boolean[][] visited = null;
    static int max = 0;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        map = new int[n][n];
        int maxNumber = 0;
        for (int i=0; i<n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int j=0; j<n; j++) {
                int tmp = Integer.parseInt(st.nextToken());
                maxNumber = Math.max(maxNumber, tmp);
                map[i][j] = tmp;
            }
        }

        for (int water=0; water<maxNumber; water++) {
            int count = 0;
            visited = new boolean[n][n];
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    if (!visited[j][k] && map[j][k] > water) {
                        bfs(k, j, water);
                        count++;
                    }
                }
            }

            max = Math.max(max, count);
        }

        System.out.println(max);
    }

    static Queue<int[]> queue = new LinkedList<>();
    static int[] directX = {1, 0, -1, 0};
    static int[] directY = {0, 1, 0, -1};
    private static void bfs(int x, int y, int maxNumber) {
        queue.add(new int[] { x, y });
        while (!queue.isEmpty()) {
            int[] pos = queue.poll();
            int curX = pos[0];
            int curY = pos[1];

            for (int i=0; i<4; i++) {
                int dx = curX + directX[i];
                int dy = curY + directY[i];

                if (dx < 0 || dx >= n || dy < 0 || dy >= n || visited[dy][dx]) continue;

                if (map[dy][dx] > maxNumber) {
                    queue.add(new int[]{dx, dy});
                    visited[dy][dx] = true;
                }
            }
        }
    }
}

This post is licensed under CC BY 4.0 by the author.

[프로그래머스] 전화번호 목록

Generics

Comments powered by Disqus.