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 == matrix[i].length

1 <= m, n <= 10

-100 <= matrix[i][j] <= 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是列数。

相关推荐
BUG收容所所长2 分钟前
栈的奇妙世界:从冰棒到算法的华丽转身
前端·javascript·算法
有风南来3 分钟前
算术图片验证码(四则运算)+selenium
自动化测试·python·selenium·算术图片验证码·四则运算验证码·加减乘除图片验证码
wangjinjin1803 分钟前
Python Excel 文件处理:openpyxl 与 pandas 库完全指南
开发语言·python
XRZaaa8 分钟前
常见排序算法详解与C语言实现
c语言·算法·排序算法
@我漫长的孤独流浪12 分钟前
数据结构测试模拟题(4)
数据结构·c++·算法
智驱力人工智能15 分钟前
智慧零售管理中的客流统计与属性分析
人工智能·算法·边缘计算·零售·智慧零售·聚众识别·人员计数
Yxh181377845541 小时前
抖去推--短视频矩阵系统源码开发
人工智能·python·矩阵
WindSearcher1 小时前
大模型微调相关知识
后端·算法
Humbunklung1 小时前
PySide6 GUI 学习笔记——常用类及控件使用方法(多行文本控件QTextEdit)
笔记·python·学习·pyqt
取酒鱼食--【余九】2 小时前
rl_sar实现sim2real的整体思路
人工智能·笔记·算法·rl_sar