2차원 M x N 배열을 나선형(spiral)으로 순회해야 합니다.
matrix.length
)가 M, 가로 길이(matrix[i].length
)가 N인 2차원 배열matrix[i]
는 string
타입을 요소로 갖는 배열matrix[i][j].length
는 1string
타입을 리턴해야 합니다.let matrix = [
['A', 'B', 'C'],
['D', 'E', 'F'],
['G', 'H', 'I'],
];
let output = spiralTraversal(matrix);
console.log(output); // --> 'ABCFIHGDE'
matrix = [
['T', 'y', 'r', 'i'],
['i', 's', 't', 'o'],
['n', 'r', 'e', 'n'],
['n', 'a', 'L', ' '],
];
output = spiralTraversal(matrix);
console.log(output); // --> 'Tyrion Lannister'
const spiralTraversal = function (matrix) {
const R = matrix.length
const C = matrix[0].length
let MOVES = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0]
]
const isValid = (r, c) => r < R && r >= 0 && c < C && c >= 0
let answer = matrix[0][0]
matrix[0][0] = false
let dir = 0
let row = 0
let col = 0
while (answer.length < R * C) {
const [nextR, nextC] = MOVES[dir]
const r = row + nextR
const c = col + nextC
if (isValid(r, c) && matrix[r][c]) {
row = r
col = c
answer += matrix[row][col]
matrix[row][col] = false
} else {
dir++
if (dir > 3) dir = 0
}
}
return answer
};