달팽이 껍데기처럼 소용돌이 모양으로 숫자가 이어지는 모습이다.
2차원 배열에 대한 이해도를 묻는 문제이다.
import java.util.Scanner;
class Solution {
int[] dir_x = { 0, 1, 0, -1 }; // dir 0, 1, 2, 3이 각각 동 남 서 북.
int[] dir_y = { 1, 0, -1, 0 };
public void slug(int[][] map, int s, int x, int y, int dir) {
int N = map.length;
map[x][y] = s++;
if (N * N < s)
return;
if (dir == 0) {
if (y + 1 < N && map[x][y + 1] == 0) {
slug(map, s, x, y + 1, dir);
return;
} else if (y + 1 >= N || map[x][y + 1] != 0) {
dir++;
s--;
}
} else if (dir == 1) {
if (x + 1 < N && map[x + 1][y] == 0) {
slug(map, s, x + 1, y, dir);
return;
} else if (x + 1 >= N || map[x + 1][y] != 0) {
dir++;
s--;
}
} else if (dir == 2) {
if (y - 1 >= 0 && map[x][y - 1] == 0) {
slug(map, s, x, y - 1, dir);
return;
} else if (y - 1 < 0 || map[x][y - 1] != 0) {
dir++;
s--;
}
} else if (dir == 3) {
if (x - 1 >= 0 && map[x - 1][y] == 0) {
slug(map, s, x - 1, y, dir);
return;
} else if (x - 1 < 0 || map[x - 1][y] != 0) {
dir -= 3;
s--;
}
}
slug(map, s, x, y, dir);
}
public static void main(String args[]) throws Exception {
Solution S = new Solution();
Scanner sc = new Scanner(System.in);
int T;
T = sc.nextInt();
for (int test_case = 1; test_case <= T; test_case++) {
int N = sc.nextInt();
int[][] map = new int[N][N];
S.slug(map, 1, 0, 0, 0);
System.out.println("#" + test_case);
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.printf("%d ", map[i][j]);
}
System.out.println();
}
}
}
}