[백준 2468] 안전 영역
Algorithm/백준(BOJ)

[백준 2468] 안전 영역

반응형

[백준 2468] 안전 영역


문제 출처 : https://www.acmicpc.net/problem/2468





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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Problem2468 {
 
    static int[][] map; // 2차원 배열 생성
    static boolean[][] visited; // 방문한 영역 확인할 2차원 boolean 배열 생성
    static int n; // 배열 사이즈 받을 변수 선언
    static int[] dx = {00-11}; // 상하좌우 값 확인할 배열 선언
    static int[] dy = {-1100};
    
    public static void dfs(int x, int y, int c){ // dfs
        visited[x][y] = true// 해당 위치 방문 완료
        
        for (int i = 0; i < 4; i++) { // 상하좌우 확인
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(nx >= 0 && ny >= 0 && nx < n && ny < n){ // 배열을 벗어나지 않게 조건문 생성
                if(visited[nx][ny] == false && map[nx][ny] > c){ // 아직 방문하지 않은 곳이거나, 안잠기는 곳이면
                    dfs(nx, ny, c);
                }
            }
        }
    }
    
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        n = Integer.parseInt(br.readLine());
        
        map = new int[n][n];
        
        int max = 0;
        
        for (int i = 0; i < n; i++) {
            String[] str = br.readLine().split(" ");
            for (int j = 0; j < n; j++) {
                map[i][j] = Integer.parseInt(str[j]);
                if(max < map[i][j]){ // 최대 높이 저장
                    max = map[i][j];
                }
            }
        }
        
        int maxCount = 1;
        int cnt = 0;
        
        for (int c = 1; c <= max; c++) { // 최대 높이만큼 for문으로 안전 영역 최대 개수 찾기
            visited = new boolean[n][n];
            cnt = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if(map[i][j] > c && visited[i][j] == false){ // 안잠기는 곳이거나 한번도 방문하지 않았으면 
                        cnt++;
                        dfs(i,j,c);
                    }
                }
            }
            if (maxCount < cnt) maxCount = cnt;
        }
        
        System.out.println(maxCount);
    }
 
}
 
cs


반응형

'Algorithm > 백준(BOJ)' 카테고리의 다른 글

[백준 1260] DFS와 BFS - 인접 행렬 이용  (0) 2019.02.02
[백준 10026] 적록색약  (0) 2019.01.30
[백준 2667] 단지번호 붙이기  (0) 2019.01.29
[백준 1874] 스택 수열  (1) 2019.01.24
[백준 1057] 토너먼트  (0) 2019.01.23