×

Leetcode 59. Spiral Matrix II

96
SnailTyan
2018.07.12 11:40* 字数 30

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

1. Description

Spiral Matrix II

2. Solution

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int total = n * n;
        vector<vector<int>> matrix;
        for(int i = 0; i < n; i++) {
            vector<int> 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
Web note ad 1