✏️ 문제 설명
양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.
✏️ code
📌 dx, dy (사방 탐색 방향 배열)
: 시계방향 나선형으로 움직이기 때문에 →↓←↑ 순서대로 dx, dy 설정하였습니다.
(→: 0,+1 / ↓: +1, 0 / ←: 0, -1 / ↑: -1, 0)
📌 direction (탐색 방향 결정)
: direction 0 → 1 → 2 → 3 안에서 계속 반복될 수 있도록 (direction + 1 ) % 4 처리하였습니다.
📌 nx, ny (다음 = next x, y)
- nx = x(현재 x)+dx[direction](탐색 진행 방향)
- ny = y(현재 y)+dy[direction](탐색 진행 방향)
📌 if (nx < 0 || nx >= n || ny < 0 || ny >= n || array[nx][ny] != 0)
- nx ~ ny까지: 배열에 벗어나지 않도록
- array[nx][ny] != 0: 이미 방문한 배열에는 또 가지 않도록 if문 조건으로 처리합니다.
class Solution {
public int[][] solution(int n) {
int[][] array = new int[n][n];
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
int direction = 0, x = 0, y = 0;
for (int i = 1; i <= n*n; i++) {
array[x][y] = i;
int nx = x+dx[direction];
int ny = y+dy[direction];
if (nx < 0 || nx >= n || ny < 0 || ny >= n || array[nx][ny] != 0) {
direction = (direction+1) % 4;
nx = x+dx[direction];
ny = y+dy[direction];
}
x = nx;
y = ny;
}
return array;
}
}
반응형