접근 방법
이전에 풀었던 1780번과 유사한 문제다. 다른 점이 있다면 이전에 푼 것은 9분할, 이번 문제는 4분할 한다는 점이다.
https://edvedv.tistory.com/28?category=1038364
백준 BOJ 1780번
접근 방법 이 문제는 분할정복으로 풀면 된다. 분할정복은 따로 설명할 필요도 없이 쉬운 개념인데, 복잡한 큰 문제를 해결할 수 있는 단순한 부분 문제로 나누어 처리한 후 다시 합쳐서 해결하
edvedv.tistory.com
똑같이 재귀함수로 분할 정복하면 쉽게 풀 수 있다. 다만 출력을 괄호로 묶어서 하는 것만 신경써주면 된다.
코드
import java.util.*;
public class Main {
public static int[][] arr;
public static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
arr = new int[N][N];
for(int i = 0; i < N; i++) {
String str = in.next();
for(int j = 0; j < N; j++) {
arr[i][j] = str.charAt(j) - '0';
}
}
QuadTree(0, 0, N);
System.out.println(sb);
in.close();
}
public static void QuadTree(int row, int col, int size){
if(check(row, col, size)){
sb.append(arr[row][col]);
return;
}
int next = size / 2;
sb.append('(');
QuadTree(row, col, next);
QuadTree(row, col + next, next);
QuadTree(row + next, col, next);
QuadTree(row + next, col + next, next);
sb.append(')');
}
// 같은 숫자인지 체크하는 메소드
public static boolean check(int row, int col, int size) {
int num = arr[row][col];
for(int i = row; i < row + size; i++){
for(int j = col; j < col + size; j++){
if(num != arr[i][j]) return false;
}
}
return true;
}
}
'알고리즘 > Class 3' 카테고리의 다른 글
백준 BOJ 2579번 - 계단 오르기 (0) | 2022.08.29 |
---|---|
백준 BOJ 2178번 - 미로 탐색 (0) | 2022.08.28 |
백준 BOJ 1931번 (0) | 2022.08.22 |
백준 BOJ 1927번 (0) | 2022.08.21 |
백준 BOJ 1780번 (0) | 2022.08.20 |
댓글