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
相关推荐
用户0332126663671 分钟前
Python 实现 Word/TXT 互转:附完整代码
python
七牛云行业应用2 分钟前
Jev 报 401 / api_key_required 怎么解决:TypeSafe AI 官方错误码表与排查步骤
算法·github
常山云栈9 分钟前
Anaconda和uv的区别是什么?
python·anaconda·uv
晴天的雨.99214 分钟前
【C++算法】三数之和
开发语言·c++·算法
AC赳赳老秦23 分钟前
公开 CSV 数据集批量处理实战:用 OpenClaw 高效完成下载、清洗与标准化分析样本生成
java·开发语言·汇编·c++·python·deepseek·openclaw
尹人入圣33 分钟前
市面上靠谱的IP驱动产业新场景新工具哪个好
网络·python·网络协议·tcp/ip
j7~1 小时前
【Python】(篇七)《使用Python库》 -- 详解
开发语言·后端·python·编程学习·python标准库·python第三方库·python拓展
多多爱学习1 小时前
括号有几层?得看还有多少个左括号没闭合
c语言·c++·算法·面试
databook1 小时前
手把手带你走一遍:机器学习模型如何用FastAPI和Docker部署
python·docker·fastapi
续写烂尾1 小时前
MK SD NAND(贴片式TF卡)替代Nor Flash:1Gb容量与256Mb Nor
算法·microsoft