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
相关推荐
m0_726365834 分钟前
哈希分分预测系统 打造自适应趋势分析「Python+DeepSeek+PyQt5」
python·qt·哈希算法
vyuvyucd14 分钟前
Qwen-1.8B-Chat昇腾Atlas800TA2部署实战
python
bubiyoushang88819 分钟前
MATLAB实现雷达恒虚警检测
数据结构·算法·matlab
轻竹办公PPT20 分钟前
2026 年工作计划 PPT 内容拆解,对比不同 AI 生成思路
人工智能·python·powerpoint
wu_asia23 分钟前
编程技巧:如何高效输出特定倍数数列
c语言·数据结构·算法
AlenTech31 分钟前
207. 课程表 - 力扣(LeetCode)
算法·leetcode·职场和发展
癫狂的兔子32 分钟前
【Python】【Flask】抽奖功能
开发语言·python·flask
linuxxx1101 小时前
python变量引用的小案例
python
一碗姜汤1 小时前
【统计基础】卡尔曼滤波,矩阵对迹求导,Joseph Form,条件数
线性代数·矩阵
2501_936146041 小时前
烟草叶片病害检测_YOLO11-C3k2-MSBlock模型详解
python