Problem Solving/Baekjoon

[백준 / BOJ] 1992 쿼드트리

msmn 2021. 3. 16. 02:27
728x90

알고리즘 분류: 재귀, 분할정복

문제 링크: www.acmicpc.net/problem/1992

 

1992번: 쿼드트리

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

www.acmicpc.net

  • 재귀로 구현할 때 여는 괄호 위치를 잘 잡아줘야한다.
  • 사이즈 만큼 정사각형을 압축 성공했으면 다시 재귀가 돌지 않도록 함수를 끝내주어야 한다.(return으로 종료)

 

#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <iostream>
#include <climits>
#include <cstring>
#include <iomanip>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>

#define ll long long
#define INF 1e9

using namespace std;

//https://www.acmicpc.net/problem/1992 쿼드트리

int n;
int ar[100][100];

void go(int size, int x, int y) {
    if(size == 0) return;
    int start = ar[x][y];
    int flag = 0;
    for(int i=x; i<x+size; i++) {
        for(int j=y; j<y+size; j++) {
            if(start != ar[i][j]) {
                flag = 1;
                break;
            }
        }
        if(flag) break;
    }
    
    if(!flag) {
        cout << start;
        return; //현재 사이즈만큼 압축 성공시 아래 재귀돌면 안됨
    }
    cout << "(";
    size /= 2;
    go(size, x, y);
    go(size, x, y+size);
    go(size, x+size, y);
    go(size, x+size, y+size);
    cout << ")";
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    cin >> n;
    string s;
    for(int i=0; i<n; i++) {
        cin >> s;
        for(int j=0; j<n; j++) {
            ar[i][j] = s[j] - '0';
        }
    }
    go(n, 0, 0);
    
    return 0;
}

 

 
728x90