LeetCode 54 Spiral Matrix 解题思路和python代码

题目:

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

Input: matrix = \[1,2,3,4,5,6,7,8,9]

Output: 1,2,3,6,9,8,7,4,5

Example 2:

Input: matrix = \[1,2,3,4,5,6,7,8,9,10,11,12]

Output: 1,2,3,4,8,12,11,10,9,5,6,7

Constraints:

m == matrix.length

n == matrixi.length

1 <= m, n <= 10

-100 <= matrixij <= 100

题目解析:

这道题目要求我们遍历 matrix 中的每个元素,用一个螺旋形的顺序。我们需要从外层到内层,遍历 matrix 中的每个元素。

我们会使用以下4个指针。

top: 从0开始,指向 matrix 的第一行。

bottom: 从 m-1 开始,指向 matrix 的最后一行。

left: 从0开始,指向 matrix 的第一列。

right: 从 n-1 开始,指向matix 的最后一列。

python 复制代码
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        result = []
        if not matrix:
            return result
        
        top, bottom = 0, len(matrix)-1
        left, right = 0, len(matrix[0]) - 1

        while top <= bottom and left <= right:
            # Traverse from left to right across the top row
            for i in range(left, right+1):
                result.append(matrix[top][i])
            top += 1

            # Traverse down the right column
            for i in range(top, bottom+1):
                result.append(matrix[i][right])
            right -= 1

            if top <= bottom:
                # Traverse from right to left across the bottom row
                for i in range(right, left-1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1
            
            if left <=  right:
                # Traverse up the left column
                for i in range(bottom, top-1, -1):
                    result.append(matrix[i][left])
                left += 1
        
        return result


        

从4个方向进行遍历:

从 matrix 的第一行,也就是顶部,从左到右,把元素添加进 result。

接着,从 matrix的最后一列,也就是最右边,从上到下,把元素添加进 result。

然后,从 matrix的最后一行,也就是底部,从右到左,把元素添加进result。

最后,从 matrix的第一列,也就是最左边,从下到上,把元素添加进result。

重复以上步骤,从外到内,直到把虽有元素添加完毕。

Time Complexity 是 O(m*n),其中m是行数,n是列数。

相关推荐
张张123y2 小时前
后端第十四课:Agent 记忆系统(让 Agent 记住上下文和用户,跨会话不健忘)
java·大数据·人工智能·python·agent·记忆
happylifetree7 小时前
Python67:核心语法-函数进阶-参数类型(函数作为参数)
python
小羊没烦恼!7 小时前
铁道部新客票系统设计(二)
开发语言·前端·数据库·python·oracle·c#·php
quantdash_cc8 小时前
从实时行情到价格观察表:用 Python 和 Pandas 构建策略输入数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
镜子AI8 小时前
镜子AI工程实践:用 Python 做 GEO 实体一致性审计,并自动生成 JSON-LD 结构化数据
人工智能·python·json
罗湖老棍子9 小时前
【例 1】Sightseeing Trip(信息学奥赛一本通- P1494)(洛谷-P10927)
数据结构·算法·图论·最短路·floyd·最小环
文丑颜不良啊10 小时前
LeetCode201~225题目解析
java·leetcode
stsdddd11 小时前
YOLO算法建筑工地安全帽目标检测数据集16881张:标注核对笔记
算法·yolo·目标检测
CV爱数码12 小时前
论文精读|Learned Primal-Dual:把原始–对偶算法展开成网络
图像处理·算法·计算机视觉·ct·重建·断层扫描
2601_9628857212 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python