[SWEA] 1954. 달팽이 숫자
📝 풀이 과정
🚨 주의 사항
- 달팽이 배열이 채워지는 순서는
우 → 하 → 좌 → 상 으로 고정되어 있다.
- 좌표의 경계를 벗어나거나, 숫자가 이미 존재하는 경우 방향을 전환해야 한다.
👩💻 제출 코드
import java.util.Scanner;
public class 달팽이숫자_1954 {
static int[] dx = {0, 1, 0, -1};
static int[] dy = {1, 0, -1, 0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for (int t = 1; t <= test; t++) {
int N = sc.nextInt();
int[][] snail = new int[N][N];
int value = 1;
int x = 0, y = 0;
int idx = 0;
while(value <= N * N){
snail[x][y] = value++;
int nx = x + dx[idx];
int ny = y + dy[idx];
if(nx < 0 || nx >= N || ny < 0 || ny >= N || snail[nx][ny] != 0){
idx = (idx + 1) % 4;
}
x = x + dx[idx];
y = y + dy[idx];
}
System.out.println("#" + t);
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
System.out.print(snail[i][j] + " ");
}
System.out.println();
}
}
}
}