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
相关推荐
leisoo809736 分钟前
ig50数据落盘ClickHousevsTimescaleDBvsDuckDB实测对比 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·json
卷无止境38 分钟前
FastAPI 的 Metadata 到底是什么,又牵动了哪些核心概念
后端·python
卷无止境40 分钟前
FastAPI 调试实战,从断点到生产环境的排错心法
后端·python
yaoxin5211231 小时前
503. Java 反射 - 编写 ServiceFactory 类
java·开发语言·python
AI备案指南-满满2 小时前
人工智能拟人化互动服务安全自评估报告的评估要点有哪些?
人工智能·算法·安全·机器人·大模型备案·算法备案
kyrie_sakura2 小时前
python学习笔记3 -- 流程控制语句结构
笔记·python·学习
程序员小八7772 小时前
Java 快速转 Go
java·python·golang
土司大王3 小时前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
梦想的旅途24 小时前
Python实现企业微信文本消息发送
开发语言·python·企业微信