백준/재귀

BOJ 2447 -별 찍기10

누누01 2022. 11. 2. 11:01
728x90

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

 

2447번: 별 찍기 - 10

재귀적인 패턴으로 별을 찍어 보자. N이 3의 거듭제곱(3, 9, 27, ...)이라고 할 때, 크기 N의 패턴은 N×N 정사각형 모양이다. 크기 3의 패턴은 가운데에 공백이 있고, 가운데를 제외한 모든 칸에 별이

www.acmicpc.net


이번 문제는 이차원 배열과 재귀를 통해 해결할 수 있는 문제이다.

 

별이 찍히는 패턴을 분석해 보면 5번째가 항상 공백인 것을 알 수 있다.

이를 파악하기 위해 for문을 돌릴 때 checkCount 변수를 선언하여 체크한다.

또한 패턴이 반복되는 길이는 3의 배수이므로 재귀를 돌릴 때 3으로 나눈 값을 변수로 전달한다.

 

이 변수가 1이 될 때 별을 찍어주고, checkCount가 5가 될 때 공백값을 넣어주면 별이 완성된다.

 

 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    static char[][] star;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int number = Integer.parseInt(br.readLine());
        star = new char[number][number];
        StringBuilder sb = new StringBuilder();

        drawStar(0, 0, number);

        for (int i = 0; i < number; i++) {
            for (int j = 0; j < number; j++) {
                sb.append(star[i][j]);
            }
            sb.append("\n");
        }

        System.out.println(sb);
        br.close();
    }

    public static void drawStar(int x, int y, int depth) {
        if (depth == 1) {
            star[x][y] = '*';

            return;
        }

        int size = depth / 3;
        int checkCount = 0;
        for (int i = x; i < x + depth; i += size) {
            for (int j = y; j < y + depth; j += size) {
                checkCount++;

                if (checkCount == 5) {
                    drawSpace(i, j, size);
                } else {
                    drawStar(i, j, size);
                }
            }
        }
    }

    public static void drawSpace(int x, int y, int depth) {
        for (int i = x; i < x + depth; i++) {
            for (int j = y; j < y + depth; j++) {
                star[i][j] = ' ';
            }
        }
    }
}