오른쪽 (right)을 기준으로 top ~ bottom 읽음 (단, top > bottom 이라면 더 이상 읽을 수 없으므로 break)
right을 기준으로 다 읽었으므로 right 경계를 줄이기 위해 `right - 1`
마지막 행(bottom)을 기준으로 left ~ right 역순으로 읽음 (단, left > right 이라면 더 이상 읽을 수 없으므로 break)
마지막 행을 기준으로 읽었으므로 경계를 줄이기 위해 `bottom - 1`
왼쪽(left)를 기준으로 top ~ bottom을 역순으로 읽음 (단, top > bottom 이라면 더 이상 읽을 수 없으므로 break)
왼쪽 열을 기준으로 읽었으므로 경계를 줄이기 위해 `left + 1`
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
const answer = [];
while (top <= bottom && left <= right) {
for (let x = left; x <= right; x++) {
answer.push(matrix[top][x]);
}
top++;
if (top > bottom) break;
for (let y = top; y <= bottom; y++) {
answer.push(matrix[y][right]);
}
right--;
if (left > right) break;
for (let x = right; x >= left; x--) {
answer.push(matrix[bottom][x]);
}
bottom--;
if (top > bottom) break;
for (let y = bottom; y >= top; y--) {
answer.push(matrix[y][left]);
}
left++;
}
return answer;
};
결론
top, bottom, left, right 경계를 설정하여 구하는 로직을 생각하는게 어려운 것 같다.