- 문제
- 2차원 M x N 매트릭스를 나선형으로 순회하여 string으로 이어 리턴하라
- [0][0]에서 출발하여 오른쪽으로 순회한다
- 시도
- 문자열로 리턴해야 하니까, 결과를 빈 문자열에 더해줘서 그 값을 리턴하자
- while문을 이용하고, 배열의 값을 빼내어 빈 문자열에 순서대로 더해주면서 순회
- 0이 될 때까지 돌리고, 위, 오른쪽, 아래(역), 왼쪽(역)순으로 순회시키면서
- 위와 아래값은 전부 빼내어 담아줄거니까 마지막에 삭제해주면
- 값이 아직 남아있는 경우, 삭제하고 남아있는 배열이 0번으로 올라가니 다시 순회하겠지
- qwert
- yuiop
- asdfg
- hjklz
- xcvbn 을 1번 순회한다고 하면
- uio
- sdf
- jkl 이 남게 된다고 예상함
- 수도코드
const spiralTraversal = function (matrix) {
let result = '';
while (matrix.length > 0) {
let max = matrix.length - 1
while (matrix[0].length > 0) {
result = result + matrix[0].shift();
}
for (let i = 1; i < matrix.length - 1; i++) {
result = result + matrix[i].pop()
}
while (matrix[max].length > 0) {
result = result + matrix[max].pop()
}
for (let i = matrix.length - 2; i > 0; i--) {
result = result + matrix[i].shift()
}
console.log(matrix)
matrix.shift()
matrix.pop()
}
return result;
};
- 레퍼런스
const spiralTraversal = function (matrix) {
const RIGHT = [0, 1];
const DOWN = [1, 0];
const LEFT = [0, -1];
const UP = [-1, 0];
const MOVES = [RIGHT, DOWN, LEFT, UP];
const M = matrix.length;
const N = matrix[0].length;
const isValid = (row, col) => row >= 0 && row < M && col >= 0 && col < N;
let cnt = 0;
let row = 0,
col = -1;
let direction = 0;
let result = '';
while (cnt < M * N) {
const move = MOVES[direction];
const [rd, cd] = move;
row = row + rd;
col = col + cd;
while (isValid(row, col) && matrix[row][col] !== false) {
result = result + matrix[row][col];
matrix[row][col] = false;
row = row + rd;
col = col + cd;
cnt++;
}
row = row - rd;
col = col - cd;
direction = (direction + 1) % 4;
}
return result;
};