8 // N
1 1 0 0 0 0 1 1 // N x N
1 1 0 0 0 0 1 1
0 0 0 0 1 1 0 0
0 0 0 0 1 1 0 0
1 0 0 0 1 1 1 1
0 1 0 0 1 1 1 1
0 0 1 1 1 1 1 1
0 0 1 1 1 1 1 1
분할 정복

1) N * N 크기의 색종이를 이차원 배열에 입력 받기
2) 종이를 자르는 함수 divide 작성 (row, col, size)
isUniform 함수: size * size 크기의 종이가 같은 값인지 확인
public class Main {
static int N;
static int[][] paper;
static int whitePapers=0;
static int Bluepapers=0;
public static void main (String [] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// [input]
N = Integer.parseInt(br.readLine());
paper = new int[N][N];
for(int i=0; i< N; i++) {
paper [i]=Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
// [logic]
divide(0,0,N);
// [output]
System.out.println(whitePapers);
System.out.println(Bluepapers);
}
/**
* check a square with given size
* @param row : 현재 종이의 가로 방향 시작 인덱스
* @param col : 현재 종이의 세로 방향 시작 인덱스
* @param size : 현재 종이의 크기
*/
private static void divide(int row, int col, int size) {
// 종이의 각 칸이 동일한 값인지 확인
if(isUniform(row, col,size)) {
if(paper[row][col]==0) whitePapers ++;
else Bluepapers ++;
return;
}
// else
int half = size / 2;
// 4조각으로 자르기 & 각 조각에 대해 재귀 호출
divide(row,col,half); // 좌상
divide(row, col+half, half); // 우상
divide(row+half, col, half); // 좌하
divide(row+half,col+half,half); // 우하
}
// 현재 자른 종이가 모두 같은 값을 가지고 있는지 확인하는 함수
private static boolean isUniform(int row, int col, int size) {
int color = paper[row][col];
for(int i=row;i<row+size;i++) {
for(int j=col;j<col+size;j++) {
if(paper[i][j]!=color) return false;
}
}
return true;
}
}
1. 시간복잡도 = O(N²)
2. 공간복잡도 = O(N²)
3. 개선 방향
1. divide 함수의 매개변수 (parameter)
divide(row,col,half); : 인자 (argument)로 전달2. 각 조각에 대한 재귀 처리