문제: 2630번: 색종이 만들기
basic-algo-lecture/workbook/0x0B.md at master · encrypted-def/basic-algo-lecture
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iomanip> // setprecision을 사용하기 위한 헤더
#include <climits>
#include <list>
using namespace std;
int wCount = 0; // 흰색 종이 개수
int bCount = 0; // 파란색 종이 개수
void Count(int n, int x, int y, vector<vector<int>> board) {
int tmpWCount = 0; // 0 이면 흰색
for (int i = x; i < x + n; i++) {
for (int j = y; j < y + n; j++) {
if (board[i][j] == 0)
tmpWCount++;
}
}
if (tmpWCount == 0)
bCount++; // 현재 단계의 종이가 전부 파란색인거니까 파란색 색종이 개수 +1 해주기
else if (tmpWCount == n * n)
wCount++; // 현재 단계 종이 전부 흰색, 흰색 색종이 +1
else {
// 색이 섞여있는 경우
// 4개로 분할해서 탐색
int half = n / 2;
Count(half, x, y, board);
Count(half, x, y + half, board);
Count(half, x + half, y, board);
Count(half, x + half, y + half, board);
}
return;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
vector<vector<int>> board(n);
for (int i = 0; i < n; i++) {
board[i] = vector<int>(n);
for (int j = 0; j < n; j++) {
cin >> board[i][j];
}
}
Count(n, 0, 0, board);
cout << wCount << "\n" << bCount;
return 0;
}
이 문제의 핵심은 현재 단계의 종이가 모두 같은 색으로 이루어져 있으면 카운트 해주고, 그렇지 않으면 4개로 분할해서 똑같은 과정을 반복하는 거였다.
4개로 분할하는 방법은 쉽다. 현재 단계의 n 값을 2 로 나누어서 half 값을 얻는다. 그 후 현재 단계의 x, y 값에 half 값을 이용해서 4개의 경우로 Count 메서드를 호출하면 된다.
현재 단계의 색종이의 색을 확인할 땐 이중 반복문을 사용하면 되는데 범위를 입력으로 받은 x, y 값에 n 값을 더한 값으로 설정해주면 된다.
참고자료: