문제 풀이 및 개발 공간

[백준] 1992번 쿼드트리 (silver 1 본문

백준공부/java

[백준] 1992번 쿼드트리 (silver 1

gomduri43 2024. 9. 4. 21:05

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

public class Main{
    static StringBuilder sb=new StringBuilder();
    static int[][] map;
    public static void main(String[] args) throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        int n=Integer.valueOf(br.readLine());

        map=new int[n+1][n+1];
        for(int i=1; i<=n; i++){
            String a=br.readLine();
            for(int j=1; j<=n; j++){
                map[i][j]=a.charAt(j-1)-'0';
            }
        }
        divide(1,n, 1,n,n);
        System.out.println(sb.toString());
    }


    public static void divide(int cols, int cole , int rows, int rowe,int length ){
        int temp=map[rows][cols];
        int tlength=length/2;
        boolean same=true;
        for(int i=rows; i<=rowe; i++){
            for(int j=cols; j<=cole; j++){
                if(map[i][j]!=temp){
                    same=false;
                    break;
                }
            }
        }
        //영역마다 다 똑같으면 해당 숫자, 아니면 분할해서 나눠서 들어가기.
        if(same){
            if(temp==1){
                sb.append("1");
            }
            else{
                sb.append("0");
            }
        }
        
        //영역 나눌때 조심. 
        else{
            sb.append("(");
            divide(cols, cols+tlength-1, rows, rows+tlength-1 , tlength);
            divide(cols+tlength, cole, rows, rows+tlength-1 ,tlength);
            divide(cols, cols+tlength-1, rows+tlength, rowe,tlength);
            divide(cols+tlength, cole, rows+tlength, rowe,tlength);
            sb.append(")");
        }
    }
}