美文网首页
LeetCode-Spiral Matrix II

LeetCode-Spiral Matrix II

作者: 圣地亚哥_SVIP | 来源:发表于2018-09-26 14:21 被阅读0次

    以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;
        }
    };
    

    相关文章

      网友评论

          本文标题:LeetCode-Spiral Matrix II

          本文链接:https://www.haomeiwen.com/subject/amwdoftx.html