Java/코딩테스트
[ SWEA ] 1954
Bubbles
2023. 5. 19. 18:19
달팽이 숫자 문제
한 방향으로 쭉 -> 가고 더이상 못가면 방향을 전환하는 방법으로 푼다.
isValid() 함수로 검사 + 해당 칸의 값이 0인지 확인 -> 아닐 경우 방향을 전환
이 때 isValid로 먼저 검사해야한다. map[x+dirX[dir]][y+dirY[dir]]를 먼저 조건의 앞에 넣어두면 벽 벗어나는 칸일 경우 바로 ArrayOutOfBound 뜨기 때문.
각 칸에는 1~n*n의 숫자를 채워넣기.
import java.util.*;
public class Solution {
static int[] dirX = { 0, 1, 0, -1 };
static int[] dirY = { 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[][] map = new int[n][n];
int x = 0;
int y = 0;
int dir = 0;
for (int i = 1 ; i <= n*n; i++) {
map[x][y] = i;
if (!isValid(x + dirX[dir], n) || !isValid(y + dirY[dir], n) || map[x + dirX[dir]][y + dirY[dir]] != 0 ) {
dir = (dir + 1) % 4;
}
x = x + dirX[dir];
y = y + dirY[dir];
}
System.out.println("#" + t);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println("");
}
}
}
public static boolean isValid(int pos, int n) {
if (pos >= n || pos < 0 ) {
return false;
}
return true;
}
}