LeetCode Spiral Matrix (JavaScript)

2025. 11. 26. 19:57·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/spiral-matrix/description/

문제 설명

더보기

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • 100 <= matrix[i][j] <= 100

문제 풀이

1. 경계 설정

  • top : 위쪽 행 경계
  • bottom : 마지막 행 경계
  • left : 왼쪽 열 경계
  • right : 오른쪽 열 경계

2. 반복문 수행

  • `top <= bottom && left <= right` 를 조건으로 while문 실행
    • 위에 조건을 만족해야 검사할 값이 존재한다는 의미
  • 4가지 기준으로 검사 시작
    1. 맨위 행(top)을 기준으로 left ~ right 읽음
      • top을 기준으로 다 읽었으므로 다음 행을 기준으로 변경하기 위해 `top + 1`
    2. 오른쪽 (right)을 기준으로 top ~ bottom 읽음 (단, top > bottom 이라면 더 이상 읽을 수 없으므로 break)
      • right을 기준으로 다 읽었으므로 right 경계를 줄이기 위해 `right - 1`
    3. 마지막 행(bottom)을 기준으로 left ~ right 역순으로 읽음 (단, left > right 이라면 더 이상 읽을 수 없으므로 break)
      • 마지막 행을 기준으로 읽었으므로 경계를 줄이기 위해 `bottom - 1`
    4. 왼쪽(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 경계를 설정하여 구하는 로직을 생각하는게 어려운 것 같다.

 

시간 복잡도 : O(mn)

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Add Binary (JavaScript)  (0) 2025.11.27
LeetCode Plus One (JavaScript)  (0) 2025.11.27
LeetCode Maximum Subarray (JavaScript), DP  (0) 2025.11.26
LeetCode Group Anagrams (JavaScript)  (0) 2025.11.26
LeetCode Rotate Image (JavaScript), matrix 회전  (0) 2025.11.26
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Add Binary (JavaScript)
  • LeetCode Plus One (JavaScript)
  • LeetCode Maximum Subarray (JavaScript), DP
  • LeetCode Group Anagrams (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (215) N
      • 프론트엔드 (65) N
        • JavaScript (52) N
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (128) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (39) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Spiral Matrix (JavaScript)
상단으로

티스토리툴바