반응형
[문제 풀이]
1. 예제를 보고 규칙 유추
2. 규칙 : 별로 찍힌 정사각형이 가로 4칸 세로 4칸씩 커짐 (N = 1 -> 가로 1, 세로 1 / N = 2 -> 가로 5, 세로 5 / N = 3 -> 가로 9, 세로 9)
3. N을 입력받아서 최댓값 = (N-1)*4+1을 시작으로 재귀를 통해 가로 -4칸 세로 -4칸씩 하면서 정사각형을 찍음
[코드]
- N을 입력받아서 (N-1)*4+1을 시작으로 재귀를 통해 가로 -4칸 세로 -4칸씩 하면서 정사각형을 찍음
void re(int x, int y, int cnt) {
if(cnt <= 0) return;
for(int i=x; i<x+cnt; i++){
for(int j=y; j<y+cnt; j++){
if(i == x || i == x+cnt-1){
arr[i][j] = 1;
continue;
}
if(j == y || j == y+cnt-1){
arr[i][j] = 1;
}
}
}
re(x+2, y+2, cnt-4);
}
- 배열에 1인 값들은 "*"로 출력하고 0인 값은 " "으로 출력
for(int i=0; i<tmp; i++){
for(int j=0; j<tmp; j++){
if(arr[i][j] == 1){
cout<<"*";
}else{
cout<<" ";
}
}
cout<<"\n";
}
[전체 코드]
#include <iostream>
using namespace std;
int arr[1000][1000] = {0, };
void re(int x, int y, int cnt) {
if(cnt <= 0) return;
for(int i=x; i<x+cnt; i++){
for(int j=y; j<y+cnt; j++){
if(i == x || i == x+cnt-1){
arr[i][j] = 1;
continue;
}
if(j == y || j == y+cnt-1){
arr[i][j] = 1;
}
}
}
re(x+2, y+2, cnt-4);
}
int main(){
int N, tmp;
cin>>N;
tmp = (N - 1) * 4 + 1;
re(0, 0, tmp);
for(int i=0; i<tmp; i++){
for(int j=0; j<tmp; j++){
if(arr[i][j] == 1){
cout<<"*";
}else{
cout<<" ";
}
}
cout<<"\n";
}
return 0;
}
https://www.acmicpc.net/problem/10994
반응형
'Algorithm > Baekjoon' 카테고리의 다른 글
[ 백준 20114 ] 미아 노트 (C++) (0) | 2025.04.10 |
---|---|
[ 백준 9037 ] The candy war (C++) (0) | 2025.03.22 |
[ 백준 2503 ] 숫자 야구 (C++) (0) | 2025.02.15 |
[ 백준 1431 ] 시리얼 번호 (C++) (0) | 2025.02.10 |
[ 백준 1388 ] 바닥 장식 (JAVA) (0) | 2025.01.31 |