Post

[BaekJoon] 17478번 - 재귀함수가 뭔가요? [Java][C++]

[BaekJoon] 17478번 - 재귀함수가 뭔가요? [Java][C++]

문제 링크


1. 아이디어


주어진 출력에 맞게 재귀 함수를 구성하면 되는 문제로 재귀 깊이만큼 앞에 언더 바를 출력하는 점만 유의하면 된다.


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
import java.io.*;

public class Main {

    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());

        bw.write("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.\n");
        dfs(0, n);

        bw.flush();
    }

    static void dfs(int depth, int n) throws IOException {
        if (depth == n) {
            bw.write("____".repeat(depth));
            bw.write("\"재귀함수가 뭔가요?\"\n");
            bw.write("____".repeat(depth));
            bw.write("\"재귀함수는 자기 자신을 호출하는 함수라네\"\n");
            bw.write("____".repeat(depth));
            bw.write("라고 답변하였지.\n");
            return;
        }

        bw.write("____".repeat(depth));
        bw.write("\"재귀함수가 뭔가요?\"\n");
        bw.write("____".repeat(depth));
        bw.write("\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.\n");
        bw.write("____".repeat(depth));
        bw.write("마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.\n");
        bw.write("____".repeat(depth));
        bw.write("그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"\n");

        dfs(depth + 1, n);

        bw.write("____".repeat(depth));
        bw.write("라고 답변하였지.\n");
    }
}


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
#include <bits/stdc++.h>
using namespace std;

void print_underbar(int x) {
    while (x--) cout << "____";
}

void dfs(int depth, int n) {
    if (depth == n) {
        print_underbar(depth);
        cout << "\"재귀함수가 뭔가요?\"\n";
        print_underbar(depth);
        cout << "\"재귀함수는 자기 자신을 호출하는 함수라네\"\n";
        print_underbar(depth);
        cout << "라고 답변하였지.\n";
        return;
    }

    print_underbar(depth);
    cout << "\"재귀함수가 뭔가요?\"\n";
    print_underbar(depth);
    cout << "\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.\n";
    print_underbar(depth);
    cout << "마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.\n";
    print_underbar(depth);
    cout << "그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"\n";

    dfs(depth + 1, n);

    print_underbar(depth);
    cout << "라고 답변하였지.\n";
}

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

    int n;
    cin >> n;

    cout << "어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.\n";
    dfs(0, n);
}

3. 디버깅


없음.


4. 참고


없음.


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