알고리즘 문제 풀이
달팽이 그리기
딩신
2018. 9. 17. 19:04
spiral (II.cpp)
문제
1 부터 나선 형 모양으로 배열에 값을 넣은 후 출력하는 프로그램을 작성하시오.
입력
입력은 배열의 크기 n 이 주어진다. n * n 행 배열이다. ( 3 <= n <= 25)
출력
각 숫자 사이 한 칸의 공백을 가지고 나선형(달팽이) 배열을 출력한다.
예제 입력
3
예제 출력
1 2 3
8 9 4
7 6 5
예제 입력
6
예제 출력
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
//코드
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//총 몇개의 숫자를 입력 받을 것인지
int a = 0;
// int b = 0;
// int c = 0;
a = sc.nextInt();
// b = sc.nextInt();
// c = sc.nextInt();
int[][] box = new int[a+1][a+1];
//direction 이 1일 땐 가로이동 / 0일때는 세로 이동
int right_direction = 1;
int bottom_direction = 0;
int right = 0;
int bottom = 1;
for(int i = 1 ; i <= a*a ; i++) {
if(right_direction == 1 && bottom_direction == 0) {
if(right+right_direction > a || box[right+right_direction][bottom] != 0) {
right_direction = 0; bottom_direction = 1;
}
}else if(right_direction == 0 && bottom_direction == 1) {
if(bottom+bottom_direction > a || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = -1; bottom_direction = 0;
}
}else if(right_direction == -1 && bottom_direction == 0) {
if(right+right_direction < 1 || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = 0; bottom_direction = -1;
}
}else if(right_direction == 0 && bottom_direction == -1) {
if(bottom+bottom_direction < 1 || box[right+right_direction][bottom+bottom_direction] != 0) {
right_direction = 1; bottom_direction = 0;
}
}
right = right+right_direction;
bottom = bottom+bottom_direction;
box[right][bottom] = i;
}
for(int i = 1 ; i<= a ; i++) {
for(int j = 1 ; j <= a; j++) {
System.out.print(box[j][i]+" ");
}
System.out.println("");
}
}
}