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
相关推荐
himobrinehacken6 分钟前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
SEO_juper8 分钟前
hreflang 审计工具:外贸多语言站谷歌SEO的隐性杀手
开发语言·人工智能·爬虫·python·seo
打工仔折腾 AI32 分钟前
从零开始大模型微调:基于 PyTorch 与 ChatGLM 的 LoRA 实践指南
人工智能·pytorch·后端·python·深度学习·性能优化·ai agent 实战
INGNIGHT38 分钟前
815 · 课程表IV(dfs)
算法·深度优先
用户03321266636739 分钟前
Python 自动化办公:如何从零快速生成结构清晰的 Excel 报表
python·excel
刘 大 望1 小时前
Agent 的规划与执行范式:Plan-Execute-Replan 与 ReAct
java·python·ai·chatgpt·langchain·ai编程
Pniubi1 小时前
力扣146.LRU缓存机制
算法·leetcode·缓存
在世修行1 小时前
智学文枢:数据备份与恢复
python·数据安全·备份恢复·zipfile
云上工程笔记1 小时前
2026年7B到67B模型训练与推理GPU配置评测:LoRA、量化与全量微调对比
人工智能·算法·机器学习
softlgh1 小时前
鼾声识别:嵌入式离线鼾声检测 SDK 与睡眠健康数据
算法·智能家居·智能音箱·鼾声识别·智能枕头·打呼噜