문제
N×N크기의 행렬로 표현되는 종이가 있다. 종이의 각 칸에는 -1, 0, 1 중 하나가 저장되어 있다. 우리는 이 행렬을 다음과 같은 규칙에 따라 적절한 크기로 자르려고 한다.
- 만약 종이가 모두 같은 수로 되어 있다면 이 종이를 그대로 사용한다.
- (1)이 아닌 경우에는 종이를 같은 크기의 종이 9개로 자르고, 각각의 잘린 종이에 대해서 (1)의 과정을 반복한다.
이와 같이 종이를 잘랐을 때, -1로만 채워진 종이의 개수, 0으로만 채워진 종이의 개수, 1로만 채워진 종이의 개수를 구해내는 프로그램을 작성하시오.
입력
첫째 줄에 N(1 ≤ N ≤ 37, N은 3k 꼴)이 주어진다. 다음 N개의 줄에는 N개의 정수로 행렬이 주어진다.
출력
첫째 줄에 -1로만 채워진 종이의 개수를, 둘째 줄에 0으로만 채워진 종이의 개수를, 셋째 줄에 1로만 채워진 종이의 개수를 출력한다.
해결 방법
접근 방식
- 분할정복, 재귀 문제
- 종이는 n x n 크기, 3의 배수, 종이의 값이 모두 같지 않으면 9개로 자른다.
- 종이의 모든 값을 확인하는 메서드가 필요하다.
- 종이의 모든 값이 같으면
- 종이의 값이 -1일 때 minus + 1
- 종이의 값이 0일 때 zero + 1
- 종이의 값이 1일 때 plus + 1
- 종이의 값이 -1일 때 minus + 1
- 종이의 모든 값이 같지 않으면 9등분으로 쪼갠다.
- size = size / 3
코드
// 종이의 개수, 1780
public class Week05_1780 {
static String[][] input;
static int minus;
static int zero;
static int plus;
public static void main(String[] args) throws IOException {
input = inputPaper();
partition(0, 0, input.length);
showOutPut();
}
private static void partition(int y, int x, int size) {
if (checkNum(y, x, size)) {
if (input[y][x].equals("-1")) {
minus++;
} else if (input[y][x].equals("0")) {
zero++;
} else if (input[y][x].equals("1")) {
plus++;
}
return;
}
size = size / 3;
partition(y, x, size); // 왼쪽 상단
partition(y, x + size, size); // 중앙 상단
partition(y, x + size * 2, size); // 오른쪽 상단
partition(y + size, x, size); // 왼쪽
partition(y + size, x + size, size); // 중앙
partition(y + size, x + size * 2, size); // 오른쪽
partition(y + size * 2, x, size); // 왼쪽 하단
partition(y + size * 2, x + size, size); // 중앙 하단
partition(y + size * 2, x + size * 2, size); // 오른쪽 하단
}
private static boolean checkNum(int y, int x, int size) {
String value = input[y][x];
for (int i = y; i < y + size; i++) {
for (int j = x; j < x + size; j++) {
if (!input[i][j].equals(value)) {
return false;
}
}
}
return true;
}
private static String[][] inputPaper() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
input = new String[n][n];
for (int i = 0; i < n; i++) {
input[i] = br.readLine().split(" ");
}
return input;
}
private static void showOutPut() throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
bw.write(minus + "\n");
bw.write(zero + "\n");
bw.write(plus + "");
bw.flush();
bw.close();
}
}
'algorithm' 카테고리의 다른 글
| [BOJ] 11728. 배열 합치기 (0) | 2022.11.17 |
|---|---|
| [BOJ] 1629. 곱셈 (0) | 2022.11.16 |
| [BOJ] 1992. 쿼드 트리 (0) | 2022.11.16 |
| [BOJ] 2630. 색종이 만들기 (0) | 2022.11.16 |
| [BOJ] 11478. 서로 다른 부분 문자열의 개수 (0) | 2022.11.06 |