螺旋矩阵 II

描述

给你一个数n生成一个包含1-n^2的螺旋形矩阵

样例

n = 3
矩阵为:

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

思考

  1. 上下左右都有边界,按照顺序 (向右,向下,向左,向上) 一个轮回,边界不断缩小,所以设置了四个变量表示边界,数字递增直到填满

代码

//  By Lentitude


class Solution {
public:
    /**
     * @param n an integer
     * @return a square matrix
     */
    vector<vector<int>> generateMatrix(int n) {
        // Write your code here
        // 初始化 vector 二维动态数组
        vector<vector<int> > vec(n);
        for (int i = 0; i != n; ++i){
            vec[i].resize(n);
        }

        int value = 1;
        int x = 0;
        int x_left = 0;         //  起始的 X 索引位置
        int x_right = n - 1;    // 结束的 X 索引位置

        int y = 0;
        int y_top = 0;          // 起始的 Y 索引位置
        int y_bottom = n - 1;   // 结束的 Y 索引位置


        while (value <= n*n){

            // 000 -> 123
            while (x <= x_right  && vec[y_top][x] == 0){
                vec[y_top][x++] = value++;
            }

            // if (vec[(n + 1)/2 - 1] == n*n){
            //     return vec;
            // }

            y_top++;
            y = y_top;

            /**
             * 3  ->   3
             * 0       4
             * 0       5
             */ 

            while (y <= y_bottom && vec[y][x_right] == 0){
                vec[y++][x_right] = value++;
            }

            x_right--;
            x = x_right;


            /**
             * 005 -> 765
             */

            while (x >= x_left && vec[y_bottom][x] == 0){
                vec[y_bottom][x--] = value++;
            }

            y_bottom--;
            y = y_bottom;

            /**
             * 0   ->  9
             * 0       8
             * 7       7
             */ 

            while (y >= y_top && vec[y][x_left] == 0){
                vec[y--][x_left] = value++;
            }

            x_left++;
            x = x_left;
        }

        return vec;



    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值