ALGORITHM/BOJ

[백준] 1992 쿼드트리

0298 2021. 9. 29. 22:16

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

 

1992번: 쿼드트리

첫째 줄에는 영상의 크기를 나타내는 숫자 N 이 주어진다. N 은 언제나 2의 제곱수로 주어지며, 1 ≤ N ≤ 64의 범위를 가진다. 두 번째 줄부터는 길이 N의 문자열이 N개 들어온다. 각 문자열은 0 또

www.acmicpc.net

2021-09-27


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
 
public class Main1992 {
    public static int N;
    public static int[][] arr;
    public static StringBuilder sb;
    public static void solve(int n, int x, int y) {
        if(n == 1) {
            sb.append(String.valueOf(arr[x][y]));
            return;
        }
 
        if(check(n, x, y)) {
            return;
        }
 
        sb.append("(");
        solve(n/2, x, y);
        solve(n/2, x, y+n/2);
        solve(n/2, x+n/2, y);
        solve(n/2, x+n/2, y+n/2);
        sb.append(")");
    }
 
    public static boolean check(int n, int x, int y) {
        int flag = arr[x][y];
        for(int i = x; i < x + n; i++) {
            for(int j = y; j < y + n; j++) {
                if(flag != arr[i][j]) return false;
            }
        }
        sb.append(String.valueOf(flag));
        return true;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(bf.readLine().trim());
        N = Integer.parseInt(st.nextToken());
        arr = new int[N][N];
        sb = new StringBuilder();
 
        for(int i = 0; i < N; i++) {
            st = new StringTokenizer(bf.readLine());
            String str = st.nextToken();
            for(int j = 0; j < N; j++) {
                arr[i][j] = str.charAt(j) - '0';
            }
        }
        solve(N, 00);
        System.out.println(sb.toString());
    }
}
cs

#문제풀이

분할정복