
내가 작성한 코드
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num = 1;
int start = 0;
int end = n;
// 바깥쪽 사각형부터 시작해 안쪽으로 한칸씩 이동하며 채우기
while (num <= n * n) {
// 오른쪽으로 이동
for (int j = start; j < end; j++)
answer[start][j] = num++;
// 아래로 이동
for (int i = start + 1; i < end; i++)
answer[i][end - 1] = num++;
// 왼쪽으로 이동
for (int j = end - 2; j >= start; j--)
answer[end - 1][j] = num++;
// 위로 이동
for (int i = end - 2; i > start; i--)
answer[i][start] = num++;
// 다음 사각형으로 이동
start++; // 시작점 증가
end--; // 끝점 감소
}
return answer;
}
}
다른 사람의 코드
class Solution {
public int[][] solution(int n) {
int[][] answer = new int[n][n];
int num = 1; // 채워넣을 숫자 (1부터 n*n까지)
int i = 0; // 현재 위치의 행 인덱스
int j = 0; // 현재 위치의 열 인덱스
int location = 0; // 현재 방향 (0:우, 1:하, 2:좌, 3:상)
// 방향 이동을 위한 델타 배열 (우, 하, 좌, 상)
int[] locationI = { 0, 1, 0, -1 }; // 행 이동 값
int[] locationJ = { 1, 0, -1, 0 }; // 열 이동 값
// 1부터 n*n까지 숫자를 채워 넣음
while (num <= n * n) {
answer[i][j] = num++; // 현재 위치에 숫자 채움
// 다음 위치 계산
int nextI = i + locationI[location];
int nextJ = j + locationJ[location];
// 다음 위치가 경계를 벗어나거나 이미 숫자가 채워진 경우
if (nextI < 0 || nextI >= n || nextJ < 0 || nextJ >= n || answer[nextI][nextJ] != 0)
location = (location + 1) % 4; // 방향 전환 (우 → 하 → 좌 → 상 순서)
// 다음 위치로 이동
i += locationI[location];
j += locationJ[location];
}
return answer; // 완성된 나선형 배열 반환
}
}
Share article