Leetcode——数组:螺旋矩阵&59.螺旋矩阵

题目

思路

对于每层,从左上方开始以顺时针的顺序填入所有元素。假设当前层的左上角位于 (top,left),右下角位于 (bottom,right),按照如下顺序填入当前层的元素。

    从左到右填入上侧元素,依次为 (top,left) 到 (top,right)。

    从上到下填入右侧元素,依次为 (top+1,right) 到 (bottom,right)。

    如果 left<right 且 top<bottom,则从右到左填入下侧元素,依次为 (bottom,right−1) 到 (bottom,left+1),以及从下到上填入左侧元素,依次为 (bottom,left) 到 (top+1,left)。

填完当前层的元素之后,将 left 和 top 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续填入元素,直到填完所有元素为止。

代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int num=1;
        vector<vector<int>> matix(n,vector<int>(n));
        int left=0;     //左边界为0
        int right=n-1;      //右边界为n-1
        int top=0;      //上边界为0
        int bottom=n-1;     //下边界为n-1
        while(left<=right&&top<=bottom)
        {
            for(int column=left;column<=right;column++)     //当列不为最右侧列时,数字应该向右移,直到到达右侧边界为止
            {
                matix[top][column]=num;     //column是列,列是变化的,下次继续循环时,列使用变化的column,此时column是最右侧节点
                num++;
            }
            //最右上角的被遍历到了,下一个向下加一个
            for(int row=top+1;row<=bottom;row++)            //当行不为下边界列时,数字应该向下移,直到到达下侧边界为止
            {
                matix[row][right]=num;          //row是变化的行,从上向下依次增加,列不变,行增加
                num++;
            }
            if(left<right&&top<bottom)
            {
                //最右下角被遍历到了,下一个向左移动一格,下一个-1
                for(int column=right-1;column>=left;column--)        //当列不为最左侧列时,列逐渐向左移动
                {
                    matix[bottom][column]=num;      //从刚才向右移动到的最远端column向左移动,行是下界bottom,移动到最左侧为止
                    num++;
                }
                for(int row=bottom-1;row>top;row--)
                {
                    matix[row][left]=num;       //列不变,行向上-1
                    num++;
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matix;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值