Leetcode 59. Spiral Matrix II

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 59. Spiral Matrix II_第1张图片
Spiral Matrix II

2. Solution

class Solution {
public:
    vector> generateMatrix(int n) {
        int total = n * n;
        vector> matrix;
        for(int i = 0; i < n; i++) {
            vector row(n, 0);
            matrix.push_back(row);
        }
        for(int i = 0, j = 0, count = 0; count < total; i++, j++) {
            // top
            for(int k = j; k < n - j; k++) {
                matrix[i][k] = ++count;
            }
            
            // right
            for(int k = i + 1; k < n - i; k++) {
                matrix[k][n - 1 - j] = ++count;
            }
            
            // bottom
            for(int k = n - 2 - j; k >= j; k--) {
                matrix[n - 1 - i][k] = ++count;
            }
            
            // left
            for(int k = n - 2 - i; k > i; k--) {
                matrix[k][j] = ++count;
            }
        }
        return matrix;
    }
};

Reference

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

你可能感兴趣的:(Leetcode 59. Spiral Matrix II)