Post

[BaekJoon] 2448번 - 별 찍기 - 11 [Java][C++]

[BaekJoon] 2448번 - 별 찍기 - 11 [Java][C++]

문제 링크


1. 아이디어


프랙탈 형태로 별을 출력하는 문제로 반복되는 구조는 아래와 같다.


높이 3인 삼각형이 반복 구조의 최소 단위이므로 이때까지 재귀를 들어가다가 방문 체크 배열에 별을 마킹해주면 된다.


2. 코드


1. 풀이 [Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.io.*;

public class Main {

    static boolean[][] vis;

    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());
        vis = new boolean[n][n * 2];

        dfs(0, 0, n);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n * 2; j++) {
                if (vis[i][j]) {
                    bw.write("*");
                } else {
                    bw.write(" ");
                }
            }
            bw.newLine();
        }

        bw.flush();
    }

    static void dfs(int sr, int sc, int n) {
        if (n == 3) {
            vis[sr][sc + 2] = true;
            vis[sr + 1][sc + 1] = true;
            vis[sr + 1][sc + 3] = true;
            vis[sr + 2][sc] = true;
            vis[sr + 2][sc + 1] = true;
            vis[sr + 2][sc + 2] = true;
            vis[sr + 2][sc + 3] = true;
            vis[sr + 2][sc + 4] = true;
            return;
        }

        dfs(sr, sc + n / 2, n / 2);
        dfs(sr + n / 2, sc, n / 2);
        dfs(sr + n / 2, sc + n, n / 2);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <bits/stdc++.h>
using namespace std;

const int MX = 3072;
bool vis[MX][MX * 2];

void dfs(int sr, int sc, int n) {
    if (n == 3) {
        vis[sr][sc + 2] = true;
        vis[sr + 1][sc + 1] = true;
        vis[sr + 1][sc + 3] = true;
        vis[sr + 2][sc] = true;
        vis[sr + 2][sc + 1] = true;
        vis[sr + 2][sc + 2] = true;
        vis[sr + 2][sc + 3] = true;
        vis[sr + 2][sc + 4] = true;
        return;
    }

    dfs(sr, sc + n / 2, n / 2);
    dfs(sr + n / 2, sc, n / 2);
    dfs(sr + n / 2, sc + n, n / 2);
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;

    dfs(0, 0, n);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n * 2; j++) {
            if (vis[i][j]) {
                cout << '*';
            } else {
                cout << ' ';
            }
        }
        cout << '\n';
    }
}

3. 디버깅


없음.


4. 참고


없음.


This post is licensed under CC BY 4.0 by the author.