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
相关推荐
圣光SG6 小时前
Java操作题练习(七)
java·开发语言·算法
_Jimmy_7 小时前
Agent 溯源精度提升方案
人工智能·python·langchain
Cx330_FCQ7 小时前
Tmux使用
服务器·git·算法
SamChan908 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
天天进步20158 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
拳里剑气8 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
颜酱8 小时前
09 | 重构项目结构
人工智能·python·langchain
ysa0510309 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1239 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
kisloy9 小时前
【爬虫入门第8讲】Python爬虫反爬入门
开发语言·爬虫·python