LeetCode54题:螺旋矩阵(python3)

路径的长度即为矩阵中的元素数量,当路径的长度达到矩阵中的元素数量时即为完整路径,将该路径返回。

循环打印: "从左向右、从上向下、从右向左、从下向上" 四个方向循环打印。

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix or not matrix[0]:
            return []
        r,c = len(matrix),len(matrix[0])
        res=[]
        left,right,top,bottom = 0,c-1,0,r-1
        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 i in range(right-1,left,-1):
                    res.append(matrix[bottom][i])
                for j in range(bottom,top,-1):
                    res.append(matrix[j][left])
            left,right,top,bottom=left+1,right-1,top+1,bottom-1
        return res
相关推荐
吴佳浩8 小时前
Python入门指南(六) - 搭建你的第一个YOLO检测API
人工智能·后端·python
superman超哥9 小时前
仓颉语言中基本数据类型的深度剖析与工程实践
c语言·开发语言·python·算法·仓颉
Learner__Q9 小时前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
————A9 小时前
强化学习----->轨迹、回报、折扣因子和回合
人工智能·python
阿昭L9 小时前
leetcode链表相交
算法·leetcode·链表
闻缺陷则喜何志丹10 小时前
【计算几何】仿射变换与齐次矩阵
c++·数学·算法·矩阵·计算几何
liuyao_xianhui10 小时前
0~n-1中缺失的数字_优选算法(二分查找)
算法
徐先生 @_@|||10 小时前
(Wheel 格式) Python 的标准分发格式的生成规则规范
开发语言·python
Mqh18076210 小时前
day45 简单CNN
python
hmbbcsm10 小时前
python做题小记(八)
开发语言·c++·算法