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
相关推荐
luj_17683 分钟前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z24 分钟前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs66635 分钟前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
刀锋00011 小时前
从0到1手搓生产级 AI Agent:LangGraph 1.2 + LangChain 1.3 保姆级实战(全部代码已跑通)
人工智能·python·langchain·ai agent·langgraph
夜雪一千1 小时前
Python 如何实现 SHA 加密?SHA1 / SHA256 / SHA512 实战教程
开发语言·python
码云骑士1 小时前
106-模型量化技术-GGUF-GPTQ-AWQ-bitsandbytes对比
python
御风之翼_唤星者1 小时前
LoadFramePackModel模块报错bad escape
python·ai
民乐团扒谱机2 小时前
【微实验】谐波乘积谱(HPS)算法深度解析:原理、数学与代码实现
开发语言·人工智能·python·算法·语音识别·音乐
Nil2082 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
小白勇闯网安圈2 小时前
Django Ajax、批量操作与分页实践
python·django