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
相关推荐
黑马水牛3 小时前
Carla仿真系列:17_利用Carla仿真环境跑通3DGS——从采集360张图到高斯泼溅建模
python·ros·colmap·3dgs·新视角合成·carla仿真·三维建图
赵大仁4 小时前
极空间 NAS 没有命令行,我逆向了它的桌面客户端
python·ai编程·nas·mcp·极空间
空白5 小时前
Power BI +VBA 【数据分析】
python
不会就选b10 小时前
算法日常・每日刷题--<贪心>14
算法
科技苑11 小时前
Python简单网络爬虫教程
爬虫·python
mmmmath_313 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z13 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
Patrick在香港13 小时前
Claude Prompt 香港场景:公文里「今日」落在 6 个日历日上,「翌日」锚错了 5 天
python·自然语言处理·正则表达式·claude·数据清洗
YsyaaabB14 小时前
Python 数值分析
python