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
相关推荐
玉鸯2 分钟前
RAG 全链路调优指南:从 Chunking 到 Reranker
python·llm·agent
圣光SG15 分钟前
Java操作题练习(二)
java·开发语言·python
m0_6174939416 分钟前
Python OpenCV 分水岭算法(Watershed)详解与实战
python·opencv·算法
海带紫菜菠萝汤16 分钟前
企业批量PDF翻译方案:从选型到部署的完整指南
人工智能·算法·pdf
Sammyyyyy17 分钟前
如何利用本地技术栈构建 0 成本 AI SaaS 雏形
开发语言·人工智能·python·ai·servbay
AAIshangyanxiu21 分钟前
Python 机器学习与深度学习气象水文海洋全域应用技术体系:地学时空数据 AI 建模、数值模式后处理、气象海洋水文智能预测与数据处理
人工智能·python·机器学习·水文气象·气象预测·气象海洋
中微极客28 分钟前
边缘AI实战:TinyML模型量化与部署全解析(TensorFlow 2.18.0 + ESP32)
人工智能·python·tensorflow
贵慜_Derek32 分钟前
vLLM-05|MLA、Compressor、Indexer 与 SWA:Flash 注意力栈在 vLLM 里怎么落地
人工智能·算法·llm
冻柠檬飞冰走茶33 分钟前
PTA基础编程题目集 7-13 日K蜡烛图(C语言实现)
c语言·开发语言·数据结构·算法
Databend41 分钟前
从全表排序到概率统计:Databend 如何用 KLL、Top-N 与 CMS 改进基数估计
大数据·数据库·算法