LeetCode-Spiral Matrix II

2018-09-26  本文已影响0人  圣地亚哥_SVIP

以spiral的顺序,填充n*n的二维序列,首先分配一个二维序列,通过外围进行填充,如下:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res;
        res.resize(n);
        for (int i=0;i<n;++i){
            res[i].resize(n);
        }
        int element = 1;
        int row=n-1;
        int col=n-1;
        for (int i=0;i<=(n-1)/2;++i){
            auto pos_r = i;
            auto pos_c = i;
            while (pos_c <= col-i){
                res[pos_r][pos_c++] = element++;
            }
            pos_c = col-i;
            pos_r++;
            while (pos_r <= row-i){
                res[pos_r++][pos_c] = element++;
            }
            pos_r = row-i;
            pos_c--;
            while (pos_c >= i){
                res[pos_r][pos_c--] = element++;
            }
            pos_c = i;
            pos_r--;
            while(pos_r > i){
                res[pos_r--][pos_c] = element++;
            }
        }
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读