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
相关推荐
朝朝辞暮i2 分钟前
C++ 第 13 课:值传递 —— 为什么函数里改了,外面却没变?
java·c++·算法
淡海水25 分钟前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
言乐632 分钟前
Python语音检索
开发语言·python·django·virtualenv·pygame
泡茶喝茶写代码1 小时前
A股量化数据工程:从 REST 接口到策略信号(第 1 篇):指数列表与实时行情接入
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据接口
happylifetree1 小时前
Python34-35:核心语法-流程控制语句-循环-综合案例
python
吃饱了得干活1 小时前
Agent 的记忆与工具:从上下文窗口到 MCP
python·agent·mcp
无忧.芙桃1 小时前
C++语言原理与实践(十):vector类的底层实现
开发语言·c++·算法
乐迪信息2 小时前
AI防爆摄像机,监测港口船舶航行偏航隐患
大数据·人工智能·深度学习·算法·计算机视觉
燐妤2 小时前
LangGraph-复习总览
python·ai·面试·agent·学习方法·langgraph
尹人入圣2 小时前
市面上IP驱动产业新场景新工具
运维·网络·python·tcp/ip