LeetCode 59. Spiral Matrix II

描述

螺旋形遍历矩阵,把1~n^2的值依次序放在矩阵中

解决

遍历


class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int st_r = 0, ed_r = n - 1;
        int st_c = 0, ed_c = n - 1;
        int cnt = 1;
        while (true)
        {
            //向右
            for (int j = st_c; j <= ed_c; ++j)
            {
                res[st_r][j] = cnt++;
            }
            ++st_r;
            if (st_r > ed_r)
                break;
            //向下
            for (int i = st_r; i <= ed_r; ++i)
            {
                res[i][ed_c] = cnt++;
            }
            --ed_c;
            if (ed_c < st_c)
                break;
            //向左
            for (int j = ed_c; j >= st_c; --j)
            {
                res[ed_r][j] = cnt++;
            }
            --ed_r;
            if (ed_r < st_r)
                break;
            //向上
            for (int i = ed_r; i >= st_r; --i)
            {
                res[i][st_c] = cnt++;
            }
            ++st_c;
            if (st_c > ed_c)
                break;
        }
        return res;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值