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
相关推荐
随意起个昵称2 小时前
区间dp-基础题目1(石子合并)
算法·动态规划
吞下星星的少年·-·3 小时前
线段树模板
算法
星空椰3 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
段一凡-华北理工大学3 小时前
2026 高炉炼铁智能化技术全景与演进路径~系列文章11:演进路径与行业未来
大数据·网络·人工智能·算法·工业智能体·高炉炼铁智能化
凯瑟琳.奥古斯特3 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
风之所往_3 小时前
Python 3.4 新特性全面总结
python
叶小鸡3 小时前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
星马梦缘4 小时前
aaaaa
数据结构·c++·算法
太阳上的雨天4 小时前
任何格式的文件转Markdown
python·ai
yaoxin5211234 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python