PS/Problems

[Java] 백준 2630번 - DFS

CalicoCat22 2021. 12. 26. 22:03

import java.util.*;
import java.io.*;

public class s3_2630{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int N = Integer.parseInt(br.readLine());
        boolean[][] color = new boolean[N][N];

        for (int i = 0; i < N; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++){
                if (Integer.parseInt(st.nextToken()) == 0){
                    color[i][j] = true;
                }
            }
        }
        // white : true, black : false

        int[] count = new int[2];
        // count[0] : white, count[1] : black
        dfs(color, count, 0, 0, N); 

        System.out.printf("%d\n%d", count[0], count[1]);
    }

    public static void dfs(boolean[][] color, int[] count, int row, int col, int size){
        int temp = check(color, row, col, size);
        if (temp == -1){
            dfs(color, count, row, col, size / 2);
            dfs(color, count, row + size / 2, col, size / 2);
            dfs(color, count, row, col + size / 2, size / 2);
            dfs(color, count, row + size / 2, col + size / 2, size / 2);
        }
        else{
            count[temp]++;
        }
    }

    public static int check(boolean[][] color, int row, int col, int size){
        boolean flag = color[row][col];

        for (int i = row; i < row + size; i++){
            for (int j = col; j < col + size; j++){
                if (flag != color[i][j]){
                    return -1;
                }
            }
        }

        if (color[row][col]){
            return 0;
        }
        else{
            return 1;
        }
    }
}