알고리즘/DFS, BFS, 시뮬, 백트래킹

[백준] 2630번 색종이 만들기

VIPeveloper 2022. 5. 17. 00:22
728x90
반응형
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int [][] arr = new int[n][n];

        for (int i = 0; i < n; i++) {
            String[] s = br.readLine().split(" ");
            for (int j = 0; j < n; j++) {
                arr[i][j] = Integer.parseInt(s[j]);
            }
        }
        solution(n,arr,0,0);
        System.out.println(white);
        System.out.println(black);
    }

    static int white;
    static int black;

    private static void solution(int size, int[][] arr,int x,int y) {
        int blackOrWhite = arr[x][y];
        if(size==1){
            if(blackOrWhite==0){
                white++;
            }else{
                black++;
            }
            return;
        }
        boolean check = true;
        for (int i = x; i < x+size; i++) {
            for (int j = y; j < y+size; j++) {
                if(arr[i][j] != blackOrWhite){
                    check = false;
                    break;
                }
            }
            if(!check) break;
        }
        if(check){
            if(blackOrWhite==0){
                white++;
            }else{
                black++;
            }
        }else{
            solution(size/2,arr,x,y);
            solution(size/2,arr,x+(size/2),y);
            solution(size/2,arr,x,y+(size/2));
            solution(size/2,arr,x+(size/2),y+(size/2));
        }
    }
}
728x90
반응형