function solution(n) {
let answer = Array.from(Array(n), (v, i) => new Array(i+1).fill(0));
let num = 1;
let flag = 0; // 0: 아래 / 1: 오른쪽 / 2: 위
let [sx, sy, ex, ey] = [0, 0, n-1, n-1];
while (Math.min.apply(null, answer.map(row => Math.min.apply(Math, row))) === 0) {
if (flag === 0) {
for (let i=sx; i<=ex; i++) {
answer[i][sy] = num++;
}
sx++;
sy++;
flag++;
} else if (flag === 1) {
for (let i=sy; i<=ey; i++) {
answer[ex][i] = num++;
}
ex--;
ey--;
flag++;
} else if (flag === 2) {
let idx = ex;
for (let i=ey; i>=sy; i--) {
answer[idx--][i] = num++;
}
sx++;
ey--;
flag = 0;
}
}
return answer.flat();
}
이게 실행속도가 훨씬 빠름
function solution(n) {
let answer = Array.from(Array(n), (v, i) => new Array(i+1).fill(0));
let num = 1;
let [x, y] = [-1, 0];
let [dx, dy] = [[1, 0, -1], [0, 1, -1]];
let direction = 0;
while (n > 0) {
for (let i=0; i<n; i++) {
x += dx[direction % 3];
y += dy[direction % 3];
answer[x][y] = num++;
}
direction++;
n--;
}
return answer.flat();
}