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
相关推荐
apocelipes11 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
HjhIron12 小时前
面试常客:字符串算法从入门到进阶
算法·面试
用户83562907805113 小时前
使用 Python 在 PDF 中创建与管理书签
后端·python
吴佳浩14 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹15 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
MeixianAgent17 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
vivo互联网技术19 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
咕白m62520 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
浮生望21 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰21 小时前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法