백준

백준 2583 영역 구하기(Java)

Park DJ 2023. 2. 17. 21:38

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

 

2583번: 영역 구하기

첫째 줄에 M과 N, 그리고 K가 빈칸을 사이에 두고 차례로 주어진다. M, N, K는 모두 100 이하의 자연수이다. 둘째 줄부터 K개의 줄에는 한 줄에 하나씩 직사각형의 왼쪽 아래 꼭짓점의 x, y좌표값과 오

www.acmicpc.net


 

Java 코드

 


import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class Main {

  static int count;
  static int m;
  static int n;
  static int[][] arr;
  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);
    ArrayList<Integer> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
      
    m = sc.nextInt();
    n = sc.nextInt();
    int t = sc.nextInt();
    arr = new int[m][n];
    

    for(int k = 0; k < t; k++) {
      int x1 = sc.nextInt();
      int y1 = sc.nextInt();
      int x2 = sc.nextInt();
      int y2 = sc.nextInt();

      for(int i = y1; i < y2; i++) {
        for(int j = x1; j < x2; j++) arr[i][j] = 1;
      }
    }

    for(int i = 0; i < m; i++) {
      for(int j = 0; j < n; j++) {
        if(arr[i][j] == 0) {
          count = 0;
          dfs(i, j);
          list.add(count);
        }
      }
    }

    Collections.sort(list);
    sb.append(list.size()+"\n");
    for(int i = 0; i < list.size(); i++) sb.append(list.get(i)+" ");
    
    System.out.println(sb);
  }

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