Algorithm/문제풀이

[Leetcode] 59. Spiral Matrix II 문제 풀이

bluespacedev 2022. 4. 13. 14:00

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

 

Spiral Matrix II - 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

문제 내용

달팽이 처럼 진행하는 대로 배열을 만들기

 

Example 1:

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

Example 2:

Input: n = 1
Output: [[1]]

 

Constraints:

  • 1 <= n <= 20

문제 풀이

그냥 막 하면 헤깔릴거 같아서

한바퀴를 기준으로 생각해서 문제를 풀었다.

 

코드

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> mat(n, vector<int>(n, 0));
        
        int num = 1;
        int r = 0, c = 0;
        while (c < n and !mat[r][c]) {
            while (c < n and !mat[r][c]) {
                mat[r][c++] = num++;
            }
            c--;
            r++;
            while (r < n and !mat[r][c]) {
                mat[r++][c] = num++;
            }
            r--;
            c--;
            while (c >= 0 and !mat[r][c]) {
                mat[r][c--] = num++;
            }
            c++;
            r--;
            while (r >= 0 and !mat[r][c]) {
                mat[r--][c] = num++;
            }
            r++;
            c++;
        }
        
        return mat;
    }
};