Leetcode每日一题:54. 螺旋矩阵

问题描述

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
在这里插入图片描述

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
在这里插入图片描述

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路分析及代码实现

这道题可以按照每层进行遍历,从最外面一层一层一层向里面遍历,
当用四个变量left,right,top,bottom来表示层的四个顶点
第一层也就是最外面一层:
一开始从左向右:从left->right+1
然后从上向下:从top+1->bottom
然后当left<right 和 top<bottom时:
从右向左:从right-1->left
然后从下向上:从bottom-1->top
所有均为下标

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return list()
        row = len(matrix)
        column = len(matrix[0])
        left,right,top,bottom = 0,column-1,0,row-1
        res = []
        while left <= right and top <= bottom:
            for i in range(left, right+1):
                res.append(matrix[top][i])
            for j in range(top+1, bottom+1):
                res.append(matrix[j][right])
            if left < right and top < bottom:
                for k in range(right-1,left, -1):
                    res.append(matrix[bottom][k])
                for h in range(bottom,top, -1):
                    res.append(matrix[h][left])
            left,right,top,bottom =  left+1, right-1, top+1, bottom-1
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会写代码的嘤嘤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值