문제

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

 

Spiral Matrix - LeetCode

Can you solve this real interview question? Spiral Matrix - Given an m x n matrix, return all elements of the matrix in spiral order.   Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Outpu

leetcode.com

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

=> m x n 행렬이 주어지면 행렬의 모든 원소를 나선형 순서로 반환하라.

 

 

문제 풀이

2차열 배열을 나선형 순서로 순회하는 문제이다.

1. 위쪽 가로줄

2. 오른쪽 세로줄

3. 아래쪽 가로줄

4. 왼쪽 세로줄

1~4까지 순서대로 순회하면 되는데, 단 3, 4번에서 1, 2를 방문했는지 체크해야 한다. 

예를 들어보자.
3번을 순회하는데 top이 bottom을 넘으면 이미 위쪽 가로줄을 방문한 상태이므로 아래로 내려갈 필요가 없다.

또 4번을 순회하는데 left가 right을 넘으면 이미 오른쪽 세로줄을 방문한 상태이므로 왼쪽으로 이동할 필요가 없다.

 

해당 규칙만 알고 문제를 풀면 된다.

 

 

 

코드

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function(matrix) {
    if (!matrix || matrix.length === 0) {
        return [];
    }

    const result = [];
    let top = 0;
    let right = matrix[0].length - 1;
    let bottom = matrix.length - 1;
    let left = 0;

    while (top <=bottom && left <= right) {
        // 위쪽 가로줄
        for (let i=left; i<=right; i++) {
            result.push(matrix[top][i])
        }
        top++;

        // 오른쪽 세로줄
        for (let i=top; i<=bottom; i++) {
            result.push(matrix[i][right])
        }
        right--;

        // 아래 가로줄
        if (top <= bottom) {
            for (let i=right; i>=left; i--) {
                result.push(matrix[bottom][i])
            }
            bottom--;
        }

        // 왼쪽 세로줄
        if (left <= right) {
            for (let i=bottom; i>=top; i--) {
                result.push(matrix[i][left])
            }
            left ++;
        }
    }
    return result;
};

+ Recent posts