개발조각

[리트코드] 54. Spiral Matrix 본문

알고리즘🅰/리트코드

[리트코드] 54. Spiral Matrix

개발조각 2022. 10. 29. 22:36
728x90
반응형

문제

https://leetcode.com/problems/spiral-matrix/

 

Spiral Matrix - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

이번 문제는 정사각형이 아닌 직사각형일 경우에도 적용이 가능해야 돼서 그 부분을 고려하고 코드를 짜야됩니다.

 

소스코드

var spiralOrder = function(matrix) {
    let [column,  row] = [matrix.length, matrix[0].length];
    let count = column * row;
    let arr = [];
    let direction = 1;
    let [x, y] = [-1, 0];
    
    while(1){
        for(let i=0; i<row; i++){
            x += direction;
            arr.push(matrix[y][x]);
        }
        row--;
        
        if(count === arr.length) break;
        
        for(let j=0; j<column-1; j++){
            y += direction;
            arr.push(matrix[y][x]);
        }
        column--;
        direction *= -1; // 방향
    }
    return arr;
};

아마 이거 보시면 이해하시기 편하실 것 같습니다.


728x90
반응형

'알고리즘🅰 > 리트코드' 카테고리의 다른 글

[리트코드] 57. Insert Interval  (0) 2022.11.04
[리트코드] 56. Merge Intervals  (0) 2022.11.02
[리트코드] 49. Group Anagrams  (0) 2022.10.26
[리트코드] 50. Pow(x, n)  (0) 2022.10.25
[리트코드] 48. Rotate Image  (0) 2022.10.24
Comments