넘치게 채우기

[LeetCode] 54. Spiral Matrix 본문

PS/LeetCode

[LeetCode] 54. Spiral Matrix

riveroverflow 2023. 5. 9. 11:23
728x90
반응형

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

문제 유형 : 나선형 매트릭스

난이도 : Medium

 

문제

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

m X n의 매트릭스를 나선형으로 순회한 순서로 반환해라.

 

Constraints:

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

 

풀이

오른쪽으로 순회 -> 아래로 순회 -> 왼쪽으로 순회 -> 위로 순회를 반복한다. 

한번 순회할 때 구역을 [시작, 끝)으로 했다. (시작부분을 제외하고 끝부분을 포함한 순회)

그리고 [0, 0] 지점은 순회하기 전부터 넣는식으로 했다.

 

코드(C++)

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> result;
        int row = 0;
        int col = 0;
        int loop = 0;
        int cnt = 0;
        int goal = m*n;

        result.push_back(matrix[0][0]);
        cnt++;
        while (goal > cnt) {
            // Move right
            col++;
            for (int i = col; i < n; i++) {
                result.push_back(matrix[row][i]);
                cnt++;
            }
            row++;
            n--;
            col = n;

            if(goal <= cnt) break;

            // Move down
            for (int i = row; i < m; i++) {
                result.push_back(matrix[i][col]);
                cnt++;
            }
            m--;
            row = m;
            if (goal <= cnt) break;
            
            col--;
            // Move left
            for (int i = col; i >= loop; i--) {
                result.push_back(matrix[row][i]);
                cnt++;
            }
            if (goal <= cnt) break;
            row--;
            col = loop;
            
            // Move up
            for (int i = row; i >= loop + 1; i--) {
                result.push_back(matrix[i][col]);
                cnt++;
            }
            row = loop+1;
            loop++;
        }
        return result; 
    }
};
728x90
반응형