2447번: 별 찍기 - 10
재귀적인 패턴으로 별을 찍어 보자. N이 3의 거듭제곱(3, 9, 27, ...)이라고 할 때, 크기 N의 패턴은 N×N 정사각형 모양이다. 크기 3의 패턴은 가운데에 공백이 있고, 가운데를 제외한 모든 칸에 별이
www.acmicpc.net
분할 정복 알고리즘ㅇ르 사용하고 시작 할 때 ' ' 으로 초기화 시켜주고 StringBuffer를 사용해준다. 일일히 조건식 비교해가면서 넣으면 시간이 더 소모된다.
package BAEKJOON;
import java.util.Scanner;
public class SquareStar_2447 {
public static void partition(char arr[][], int n, int x, int y) {
if (n == 1) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i != 1 || j != 1)
arr[x * 3 + i][y * 3 + j] = '*';
}
}
} else {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i != 1 || j != 1)
partition(arr, n / 3, x * 3 + i, y * 3 + j);
}
}
}
}
public static void printStar(int n) {
char arr[][] = new char[n][n];
// 비교해서 ' '를 넣어주는 것보다 처음 ' '로 초기화 시키고 ' '를 넣을 때를 continue 내지 로직으로 제외 시키는 것이 더 빠르다.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = ' ';
}
}
partition(arr, n/3, 0, 0);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]);
sb.append('\n');
}
System.out.print(sb);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.close();
printStar(n);
}
}
'알고리즘' 카테고리의 다른 글
백준 Z-1074 (0) | 2020.11.08 |
---|---|
백준 설탕 배달-2839 (0) | 2020.11.08 |
백준 쿼드트리-1992 (0) | 2020.11.08 |
백준 회의실배정-1931 (0) | 2020.11.08 |
백준 미로탐색-2178 (0) | 2020.11.08 |