문제
https://www.acmicpc.net/problem/2448
2448: 별 찍기 - 11
예제를 보고 규칙을 유추한 뒤에 별을 찍어 보세요.
www.acmicpc.net
해설
- 해당 삼각형의 시작 위치를 재귀적으로 욺기며 가장 최소 단위의 삼각형이 나올 때까지 쪼갠다.
- 초기 값을 반씩 쪼개서 현재 좌표에 더해주어 시작점을 잡아준다.
여기서 행 크기는 N, 열 크기는 2 * N - 1이므로
N = 24이면 24 / 2, 48 / 2로 반씩 나누어줘야 한다. - 최소 단위의 삼각형 (n==1)이면 이를 map에 복사해준다.
- 최종적으로 출력한다.
코드 (재귀)
package com.javajava.week19;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class BOJ2448 {
static char[][] map;
static char[][] triangle = {
{' ', ' ', '*', ' ', ' '},
{' ', '*', ' ', '*', ' '},
{'*', '*', '*', '*', '*'}
};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
//3 * 2^10 = 1024 * 3 = 3072 (행)
//3 * 2^10 * 2 - 6144
map = new char[3073][6144];
int depth = N / 3;
draw(depth, 0, 0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 0; j < 2 * N ; j++) {
sb.append(map[i][j] == '*' ? '*' : ' ');
}
sb.append("\n");
}
bw.write(sb.toString());
bw.flush();
bw.close();
}
//depth = 2^n 꼴 8 = 2^3 -> 3번씩 재귀 log2(n)깊이만큼 수행해야 한다.
private static void draw(int depth, int x, int y) {
if (depth == 1){
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
map[x + i][y + j] = triangle[i][j];
}
}
return;
}
draw(depth / 2, x, y + 3 * depth / 2);
draw(depth / 2, x + 3 * depth / 2, y);
draw(depth / 2, x + 3 * depth / 2, y + 3 * depth);
}
}
결론
진짜 너무너무너무너무 어려운 문제 (답을 보고도 이해하는데 꽤나 오래 걸렸다...ㅠㅠ)
'CodingTest > 백준' 카테고리의 다른 글
[백준] BOJ 17780 새로운 게임 (골드 2) (0) | 2024.06.18 |
---|---|
[백준] BOJ 14621 나만 안되는 연애 (골드 3) (0) | 2024.06.18 |
[백준] BOJ 1389 케빈 베이컨의 6단계 법칙 (실버 1) (0) | 2024.06.18 |
[백준] BOJ 17219 비밀번호 찾기 (실버 4) (0) | 2024.06.18 |
[백준] BOJ 2638 치즈 (골드 3) (0) | 2024.06.18 |