hwangnk1004 / Algorithm

0 stars 0 forks source link

StepByStep #단지 번호 붙이기 #298

Open hwangnk1004 opened 4 years ago

hwangnk1004 commented 4 years ago

import java.util.Scanner;

public class Main {

public static int n;
public static int arr[][];
public static int cnt = 0;
public static int size[] = new int[100];

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    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();
        }
    }

    solve();
    output();

}

public static void solve() {

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[i][j] == 1) {
                cnt++;
                dfs(i, j, cnt + 1);

            }
        }
    }

    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
            if(arr[i][j] >0) {
                size[arr[i][j]-2]++;
            }
        }
    }
}

public static void dfs(int a, int b, int c) {
    arr[a][b] = c;
    if (safe(a+1,b) && arr[a+1][b] ==1) {
        dfs(a+1,b,c);
    }
    if (safe(a-1,b) && arr[a-1][b] ==1) {
        dfs(a-1,b,c);
    }
    if (safe(a,b+1) && arr[a][b+1] ==1) {
        dfs(a,b+1,c);
    }
    if (safe(a,b-1) && arr[a][b-1] ==1) {
        dfs(a,b-1,c);
    }

}

public static boolean safe(int a, int b) {

    return (0<=a && a<n) && (0<=b && b<n);
}

public static void output() {
    System.out.println(cnt);

    for(int i=0; i<cnt-1; i++) {
        for(int j=i+1; j<cnt; j++ ){
            if (size[i] > size[j]) {
                int empty =0;
                empty = size[i];
                size[i] = size[j];
                size[j] = empty;
            }
        }
    }

    for(int i=0; i<cnt; i++) {
        System.out.println(size[i]);
    }
}

}