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
相关推荐
金融小师妹6 小时前
多因子智能推演:油价回落6%与黄金震荡上行的关联解析——AI预测框架
大数据·python·深度学习
坚持编程的菜鸟8 小时前
模拟实现memmove
c语言·算法·模拟实现memmove
BUG研究员_8 小时前
Runnable与LCEL
开发语言·人工智能·python
老马聊技术8 小时前
Pytorch深度学习环境配置与测试
人工智能·pytorch·python
Python私教9 小时前
AI Agent 上生产要不要开写权限?我把执行链拆成 4 道闸门
人工智能·后端·python
天才测试猿9 小时前
软件测试知识总结(基础篇)
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
wabs6669 小时前
关于图论【最短路径之Dijkstra算法(堆优化版)|卡码网47.参加科学大会的思考】
数据结构·算法·图论·优先级队列·邻接表·小顶堆·卡码网
崔子末10 小时前
某影视库剧集列表以及查询接口逆向
爬虫·python
gogogo出发喽10 小时前
v3 admin
python