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
相关推荐
superman超哥几秒前
仓颉Actor模型的实现机制深度解析
开发语言·后端·python·c#·仓颉
superman超哥1 分钟前
仓颉内存管理深度探索:引用计数的实现原理与实战
c语言·开发语言·c++·python·仓颉
芥子沫2 分钟前
《人工智能基础》[算法篇5]:SVM算法解析
人工智能·算法·机器学习·支持向量机·svm
zhuzihuaile3 分钟前
Langchain-Chatchat + Ollama + QWen3 + 搭建知识库 + AI-Win
人工智能·python·ai·langchain
BigerBang4 分钟前
LoRA 全方位指南:从底层原理到 Qwen-Image-Edit 实战
人工智能·pytorch·深度学习·算法
passxgx7 分钟前
11.3 迭代法和预条件子
线性代数·算法·矩阵
Warson_L10 分钟前
python的__init__.py
python
shix .14 分钟前
spiderdemo 2-混淆
开发语言·python
X在敲AI代码15 分钟前
【无标题】
算法·leetcode·职场和发展
bubiyoushang88816 分钟前
NSGA-II 带精英策略的双目标遗传算法
算法