728x90
2차원 배열의 순회를 활용한 문제이다.
while 문을 활용해서 해당 방향의 index를 채우고, array의 끝을 만나거나 이미 방문된 노드를 만났을 때는 방향을 바꾸어 주었다.
각 방향을 1~4로 두고 switch문으로 케이스를 정하였다.
case 1: 오른쪽으로 이동: row는 그대로, col을 증가
case 2: 아래로 이동: col은 그대로, row를 증가
case 3: 왼쪽으로 이동: row는 그대로, col을 감소
case 4: 위로 이동: col은 그대로, row를 증가
그리고 1에서 더 나아갈 방향이 없으면 2로, 2에서 3으로 재귀적으로 snail함수를 수행하도록 하였다
그리고 함수를 실행하였을 때 이미 그 칸이 칠해져있다면, 모든 칸이 칠해진 경우이므로 return으로 종료조건을 주었다.
package SWEA0810;
import java.util.Scanner;
public class SWEA_1954_달팽이숫자 {
static int[][] nums;
static int N;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
N = sc.nextInt();
nums = new int[N][N];
int cnt = 1;
snail(0, 0, cnt, 1);
System.out.println("#" + (t + 1));
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(nums[i][j] + " ");
}
System.out.println();
}
}
}
static void snail(int i, int j, int cnt, int dir) {
if (N == 1) {
nums[i][j] = 1;
return;
}
if (nums[i][j] != 0)
return;
switch (dir) {
case 1:
while (j <= N - 1 && nums[i][j] == 0) {
nums[i][j++] = cnt++;
}
snail(i + 1, j - 1, cnt, 2);
break;
case 2:
while (i <= N - 1 && nums[i][j] == 0) {
nums[i++][j] = cnt++;
}
snail(i - 1, j - 1, cnt, 3);
break;
case 3:
while (j >= 0 && nums[i][j] == 0) {
nums[i][j--] = cnt++;
}
snail(i - 1, j + 1, cnt, 4);
break;
case 4:
while (i >= 0 && nums[i][j] == 0) {
nums[i--][j] = cnt++;
}
snail(i + 1, j + 1, cnt, 1);
break;
}
}
}
728x90
'문제 풀이 > SWEA' 카테고리의 다른 글
[SWEA] 5432 - 쇠막대기 자르기 (자바/Java) (0) | 2022.08.11 |
---|---|
[SWEA] 6190 - 정곤이의 단조 증가하는 수 (자바/Java) (0) | 2022.08.11 |
[SWEA] 1208 - Flattern (자바/Java) 배열, 우선순위 큐(힙) (0) | 2022.08.09 |
[SWEA] 4789 - 성공적인 공연 기획 (자바 / Java) (0) | 2022.08.09 |
[SWEA] 1220 - Magnetic (자바/Java) (0) | 2022.07.29 |