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
相关推荐
Navigator_Z17 分钟前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah34 分钟前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai454535 分钟前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
用户45428451062811 小时前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python
草履虫AI课1 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
用户298698530142 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api
AAA修煤气灶刘哥2 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
用户0332126663672 小时前
使用 Python 在 PDF 中创建表单域
python
凌冰_3 小时前
数据结构 - 渐进符号和递归的复杂度(二)
数据结构·算法·软件工程
Highcharts.js4 小时前
Highcharts 在商业智能中的实战应用:释放数据洞察
前端·人工智能·算法·信息可视化·数据分析·数据可视化·highcharts