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
相关推荐
ysu_031414 分钟前
19-插入排序与希尔排序
数据结构·算法·排序算法
微软技术分享15 分钟前
基于 HuggingFace Tokenizers 训练自定义分词器
python·ubuntu·大模型·huggingface
零依赖极客17 分钟前
Day 9·1 KV 也量化——q8 KV 把缓存与 decode 带宽压到一半
c语言·开发语言·arm开发·人工智能·缓存·矩阵
gf132111122 分钟前
python_调用远程服务器上的openclaw
服务器·python·php
lbb 小魔仙25 分钟前
Jupyter Notebook / Lab 深度配置指南:插件 + 内核 + 远程访问 + 容器化部署
ide·python·jupyter
2601_9623004727 分钟前
python是跨平台的吗
python·开源·跨平台·面向对象·
qq_5085760931 分钟前
人性机器人部分 算法
算法·机器人
2401_8445829532 分钟前
软件架构设计与持续重构:模块化开发实战建
python
Polevne36 分钟前
C# GRPC 一元与双向流
linux·算法·c#
huang57914739 分钟前
复杂网络中的最短路径搜索算法性能分析3
算法