BOJ 10994 | 별찍기 - 19 | 해결 과정 정리 | 재귀 vs 재귀X

2022. 3. 24. 18:47·기타

백준 10994 별찍기 문제를 해결해보았다. 

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

 

10994번: 별 찍기 - 19

예제를 보고 규칙을 유추한 뒤에 별을 찍어 보세요.

www.acmicpc.net

 

 


◆ 문제 해결 과정 : (재귀 X)

 

 

 


◆ 소스코드 (재귀X)

위 방법으로 구현한 결과

위 문제해결 과정을 바탕으로 다음처럼 작성해나갔다.

 

- draw_step_of(k) : k단계 박스를 그리는 메서드

- print_else_line(k) : k단계 박스를 그리는 메서드 안에 사용함.

                           박스 윗라인이 있는 부분 말고 다른 라인을 그린다.

                           (=> box side만을 그리는 부분)

- flag를 설정하여서 box의 윗부분, 아랫부분을 그리는 방법을 달리하였다.

  단순히, 위에 소개한 두 메서드의 순서를 서로 뒤바꿔주었을 뿐이다.

 

'박스그리기의 단계'를 문제해결의 기준으로 삼은 만큼,

메서드의 매개변수는 모두 박스의 단계 k로 통일했다.

 

import java.util.*;

public class Main{

  public static boolean flag = false;
  public static int max_stars, N;

  public static void print_else_line(int k){
    // box k개 -> 양옆에 k개의 별 찍기 (k != 3)
    // 그럼 공백은 -> max_stars - k*2*2
    if (k != N) {
      System.out.print("* ".repeat(k)
                      + " ".repeat(max_stars - k*2*2)
                      + " *".repeat(k) + "\n"); 
    }
  }
  
  public static void draw_step_of(int k, boolean flag){
    if (flag)
      print_else_line(k);
    
    // box k개 단계
    // - count of "*" or " " except line : ((k-1)*2)*2
    // - count of stars at line : max_stars - ((k-1)*2)*2
    System.out.print("* ".repeat((k-1))
                    + "*".repeat((max_stars - ((k-1)*2)*2))
                    + " *".repeat((k-1)) + "\n");
    
    if (!flag)
      print_else_line(k);
  }

  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    N = sc.nextInt();
    max_stars = (2*N-1)*2 - 1;
    sc.nextLine();

    for(int i = 1; i <= N; i++)
      draw_step_of(i, flag);

    flag = true;
    for (int i = N-1; i >= 1; i--)
      draw_step_of(i, flag);
      
    sc.close();
  }
}

 


◆ 재귀 구현

이게 훨씬 낫다.

재귀로 푼 결과

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

public class Main{
  // 1 <= input <= 100
  // max_length : (2*100-1)*2-1 => 397
  public static char[][] matrix = new char[397][397];
  public static int maxLength = 0;

  public static void recurBox(int x, int y, int step){
    if (step == 1){
      matrix[y][x] = '*';
      return;
    }
    /*
    input : 3
    step3 : line length : 9
    step2 : line length : 5
    step1 : line length : 1
    generalization : step k, line length is (2*k-1)*2-1 
    */
    int length = (2 * step - 1) * 2 - 1;
    
    for (int i = 0; i < length; i++){
      // upper, bottom line
      matrix[y][x+i] = '*';
      matrix[y+length-1][x+i] = '*';
    }
    for (int i = 0; i < length-1; i++){
      // both side line
      matrix[y+i][x] = '*';
      matrix[y+i][x+length-1] = '*';
    }
    
    recurBox(x+2, y+2, step - 1);
  }

  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());
    maxLength = (2 * n - 1) * 2 - 1;

    for(int i = 0; i < maxLength ; i++){
      for(int j = 0; j < maxLength; j++)
        matrix[i][j] = ' ';
    }
    
    recurBox(0, 0, n);

    for(int i = 0; i < maxLength; i++){
      for(int j = 0; j < maxLength; j++)
        bw.write(matrix[i][j]);
      bw.newLine();
    }
    
    br.close();
    bw.flush();
    bw.close();
  }
}
반응형

'기타' 카테고리의 다른 글

라즈베리파이 hdmi 모니터 연결 실패 | 해결과 아직 난제인 것...  (0) 2022.05.12
[Java] BOJ 2469 | 사다리타기  (0) 2022.04.05
virtualbox ubuntu 20.04 로그인 후 검은화면 해결하기  (4) 2022.03.02
DFS | 재귀함수 미로찾기 구현 (Java)  (0) 2022.02.28
티스토리 | 더보기 버튼 가운데 정렬하는 방법  (0) 2022.02.24
'기타' 카테고리의 다른 글
  • 라즈베리파이 hdmi 모니터 연결 실패 | 해결과 아직 난제인 것...
  • [Java] BOJ 2469 | 사다리타기
  • virtualbox ubuntu 20.04 로그인 후 검은화면 해결하기
  • DFS | 재귀함수 미로찾기 구현 (Java)
히어로맛쿠키
히어로맛쿠키
  • 히어로맛쿠키
    yeny_lab
    히어로맛쿠키
  • 전체
    오늘
    어제
    • 분류 전체보기 (389)
      • 미분류글 (32)
        • ㅇ (2)
      • JAVA (84)
        • Effective Java (1)
        • Application (21)
      • 컴퓨터구조 & OS (28)
      • 자료구조 + 알고리즘 (43)
      • Database (12)
      • 컴파일러 (10)
      • 수학 (33)
        • 미분방정식 (12)
      • 데이터분석과 머신러닝 (38)
      • 기타 (59)
      • yyeeennyy (25)
  • 공지사항

    • ^o^/♡
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
히어로맛쿠키
BOJ 10994 | 별찍기 - 19 | 해결 과정 정리 | 재귀 vs 재귀X
상단으로

티스토리툴바