[백준10097] 별 찍기-22 / Java

Hyeongmin Jung·2022년 12월 1일
0

java

목록 보기
13/28

링크 | https://www.acmicpc.net/problem/10997

문제 |

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

입력 |

첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.

출력 |

첫째 줄부터 차례대로 별을 출력한다.

예제 |



Solution |

  • 재귀함수 사용.
  • 별 패턴의 크기는 세로 4N-1, 가로 4N-3
  • 상단과 하단의 별을 한 세트로, 양단의 별을 한 세트로 반복하여 별을 찍어준다.
  • 맨 왼쪽 둘째 줄의 별과 오른쪽에서 한 칸옆의 별(바깥 사각형과 안쪽 사각형을 이어주는 별)은 예외적으로 찍어준다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Star_22 {
	static char[][] star;
	static int cnt = 0;
	
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine());
		
		if (N==1) { 
			star = new char[1][1];
		}else { 
			star = new char[4*N-1][4*N-3]; 
		}
		
		for (int i=0; i<star.length; i++) {
			Arrays.fill(star[i],' ');
		}

		Pattern(0, star.length-1, star[0].length-1, N);	
		System.out.print(print(star));
		br.close();
	}

	static void Pattern(int top, int bottom, int x, int N) {		
		if (N==1) {
			star[0][0] = '*';
			return;
		}else {
			if(cnt!=0) {
				star[top][x+1]='*';
			}
			if(N==2) {
				star[top+2][x-1]='*';
				star[top+2][x-2]='*';
				star[top+3][x-2]='*';
				star[top+4][x-2]='*';
			}
			star[top+1][cnt]='*';
			
			for(int j=cnt; j<=x; j++) {
				star[top][j]='*';
				star[bottom][j]='*';
			}
			for(int j=2+cnt; j<=bottom; j++) {
				star[j][cnt]='*';	
				star[j][x]='*';	
			}
			cnt += 2;
			Pattern(top+2, bottom-2, x-2, N-1);
		}		
	}
	
	static StringBuilder print(char[][] star) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < star.length; i++) {
			for (int j = 0; j < star[0].length; j++) {
				if (i==1 && j==0) {
					sb.append(star[i][j]);
					break;
				}
				sb.append(star[i][j]);
			}
			sb.append('\n');
		}
		return sb;
	}
}

0개의 댓글