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
相关推荐
xlq223224 小时前
22.多态(上)
开发语言·c++·算法
666HZ6664 小时前
C语言——高精度加法
c语言·开发语言·算法
Wise玩转AI4 小时前
Day 27|智能体的 UI 与用户交互层
人工智能·python·ui·ai·chatgpt·ai智能体
sweet丶4 小时前
iOS MMKV原理整理总结:比UserDefaults快100倍的存储方案是如何炼成的?
算法·架构
s***46984 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
云里雾里!5 小时前
力扣 209. 长度最小的子数组:滑动窗口解法完整解析
数据结构·算法·leetcode
runepic5 小时前
Python + PostgreSQL 批量图片分发脚本:分类、去重、断点续拷贝
服务器·数据库·python·postgresql
codists5 小时前
2025年11月文章一览
python
生而为虫5 小时前
31.Python语言进阶
python·scrapy·django·flask·fastapi·pygame·tornado
言之。5 小时前
Claude Code 实用开发手册
python