LeetCode | Spiral Matrix II(螺旋矩阵填充数据)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

题目解析:

先赋值一行再一列再一行最后一列,按照顺时针赋值。最后当n为奇数的时候,需要额外处理。只要细心就行了、

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int> > res;
        for(int i = 0;i < n;i++){
            vector<int> tmp = vector<int>(n,0);
            res.push_back(tmp);
        }
        int count = 1;
        for(int i = 0;i < n/2;i++){
            for(int j = i;j < n-i-1;j++)
                res[i][j] = count++;
            for(int j = i;j < n-i-1;j++)
                res[j][n-i-1] = count++;
            for(int j = n-i-1;j > i;j--)
                res[n-1-i][j] = count++;
            for(int j = n-i-1;j > i;j--)
                res[j][i] = count++;
        }
        if(n%2)
            res[n/2][n/2] = count;
        return res;
    }
};

点赞