백준

백준 2468 안전 영역(Java)

Park DJ 2023. 2. 16. 16:09

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

 

2468번: 안전 영역

재난방재청에서는 많은 비가 내리는 장마철에 대비해서 다음과 같은 일을 계획하고 있다. 먼저 어떤 지역의 높이 정보를 파악한다. 그 다음에 그 지역에 많은 비가 내렸을 때 물에 잠기지 않는

www.acmicpc.net


 

Java 코드

 


import java.util.Scanner;

public class Main {

  static int n;
  static int[][] arr;
  static boolean[][] visit;
  static int[] dx = {1, -1, 0, 0};
  static int[] dy = {0, 0, -1, 1};

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int max = -1;
    int maxcount = 0;
    n = sc.nextInt();
    arr = new int[n][n];
   
    for(int i = 0; i < n; i++) {
      for(int j = 0; j < n; j++) {
        arr[i][j] = sc.nextInt();
        max = Math.max(max, arr[i][j]);
      }
    }

    for(int k = 0; k <= max; k++) {
      visit = new boolean[n][n];
      int count = 0;
      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
          if(visit[i][j] == false && arr[i][j] > k) {
            dfs(i, j, k);
            count++;
          }
        }
      }
      maxcount = Math.max(maxcount, count);
    }

    System.out.println(maxcount);
  }

  public static void dfs(int a, int b, int h) {
    visit[a][b] = true;
    for(int i = 0; i < 4; i++) {
      int x = a + dx[i];
      int y = b + dy[i];
      if(x >= 0 && x < n && y >= 0 && y < n) {
        if(visit[x][y] == false && arr[x][y] > h) dfs(x, y, h);
      }
    }
  }
  
}