문제 링크: https://school.programmers.co.kr/learn/courses/30/lessons/68645
문제 풀이 흐름
arr[nx][ny]
값이 0이 아닌 경우 방향을 변경arr
배열에 담긴 결과를 answer
배열로 옮겨 담는다.class Solution {
private static final int[] dx = {0, 1, -1};
private static final int[] dy = {1, 0, -1};
public int[] solution(int n) {
int[][] arr = new int[n][n];
int cur = 1, d = 0, max = n * (n + 1) / 2, x = 0, y = 0;
while (cur <= max) {
arr[y][x] = cur++;
while (cur <= max) {
int nx = x + dx[d], ny = y + dy[d];
if (ny >= n || nx >= n || nx < 0 || ny < 0 || arr[ny][nx] != 0) {
d = (d + 1) % 3;
continue;
}
x = nx;
y = ny;
break;
}
}
int[] answer = new int[max];
int idx = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
answer[idx++] = arr[i][j];
}
}
return answer;
}
}