재귀가 익숙하지 않으면 풀기 힘든 문제다. 근데 알고보면 별 거 없다.


가운데

가운데
끝났다.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) { for (; b; a %= b, swap(a, b)); return a; }
char star[2201][2201] = { 0 , };
void recur(int x, int y, int cur)
{
// n = 1이면 별 찍고 리턴
if (cur == 1)
{
star[x][y] = '*';
return;
}
int next = cur / 3;
// 가운데 빼고 재귀로 돌기
// 1 2 3
// 4 6
// 7 8 9
// 항상 이렇게 이중 for문이 돈다.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) // 가운데는 스킵
continue;
else
recur(x + (i * next), y + (j * next), next);
}
}
}
int main()
{
ios::ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n;
cin >> n;
// 모두 빈칸으로 초기화
for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) star[i][j] = ' ';
// 재귀 시작
recur(0, 0, n);
// 출력
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << star[i][j];
}
cout << '\n';
}
return 0;
}
'BOJ_단계별로 풀어보기(9단계~) > [9단계] 재귀' 카테고리의 다른 글
[백준 10870] 피보나치 수 5 (0) | 2021.07.31 |
---|---|
[백준 10872] 팩토리얼 (0) | 2021.07.31 |