Mini

백준 2630 색종이 만들기 c++ // 재귀함수 , 일반식만들기 본문

Algorithm/recursion

백준 2630 색종이 만들기 c++ // 재귀함수 , 일반식만들기

Mini_96 2023. 9. 26. 15:49

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

 

2630번: 색종이 만들기

첫째 줄에는 전체 종이의 한 변의 길이 N이 주어져 있다. N은 2, 4, 8, 16, 32, 64, 128 중 하나이다. 색종이의 각 가로줄의 정사각형칸들의 색이 윗줄부터 차례로 둘째 줄부터 마지막 줄까지 주어진다.

www.acmicpc.net

1. 내 코드

#include <bits/stdc++.h>
using namespace std;

int n,ret1,ret2, a[150][150];

//시작좌표~끝좌표(시작좌표+n)까지 돌면서 모두같은지 검사
bool all_same(int n, int y, int x) {

	int first = a[y][x];
	for (int i = y; i < y + n; ++i) {
		for (int j = x; j < x + n; ++j) {
			if (a[i][j] != first) {
				return false;
			}
		}
	}

	return true;

}

//함수정의 : 크기n*n, 시작좌표 
void go(int n, int y, int x) {
	//기저사례
	if (all_same(n,y,x)) {

		if (a[y][x] == 0) {
			ret1++;
		}
		if (a[y][x] == 1) {
			ret2++;
		}

		return;
	}

	int half = n / 2;
	//재귀식
	//4칸으로 나눈후 각각칸의 시작좌표를 구했음.
	go(half, y, x);
	go(half, y, x+half);
	go(half, y+half, x);
	go(half, y+half, x+half);
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	cin >> n;

	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			cin >> a[i][j];
		}
	}

	go(n, 0, 0);

	cout << ret1 << "\n" << ret2 << "\n";

}