프로그래밍 공부

BOJ/백준 1992 쿼드트리 본문

Problem Solving/Baekjoon Online Judge

BOJ/백준 1992 쿼드트리

khj1999 2024. 9. 23. 08:48

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

 

해결 아이디어

재귀를 사용한 분할 정복 문제이다 size / 2로 범위를 좁혀가며 배열을 체크하여

정답 배열에 값을 추가하는 방식으로 문제를 해결하였다.

#include <iostream>
#include <vector>

using namespace std;
vector<char> ans;
int n;

void solve(vector<string>& grid, int size, int x, int y){
    char standard = grid[x][y];
    bool check = true;
    for(int i = x; i < x + size; i++){
        for(int j = y; j < y + size; j++){
            if(standard != grid[i][j]){
                check = false;
                break;
            }
        }
    }

    if(check){
        ans.push_back(standard);
    }
    else{
        int newSize = size / 2;
        ans.push_back('('); // 범위를 분할 할 떄 
        for(int i = 0; i < 2; i++){
            for(int j = 0; j < 2; j++){
                solve(grid, newSize, x + i * newSize, y + j * newSize);
            }
        }
        // 한 범위의 검사가 끝났을때
        ans.push_back(')');
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    int size = n;
    vector<string> grid(n);
    for(int i = 0; i < n; i++){
        cin >> grid[i];
    }

    solve(grid, size, 0, 0);
    for(auto tmp : ans){
        cout << tmp;
    }
    return 0;
}

'Problem Solving > Baekjoon Online Judge' 카테고리의 다른 글

BOJ/백준 15655 N과 M (6)  (0) 2024.10.09
BOJ/백준 17829 222-폴링  (0) 2024.09.25
BOJ/백준 2606 바이러스  (0) 2024.09.20
BOJ/백준 19591 독특한 계산기  (0) 2024.09.19
BOJ/백준 10815 숫자 카드  (1) 2024.09.17
Comments