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是列数。

相关推荐
灰灰老师12 分钟前
数据分析系列--[11] RapidMiner,K-Means聚类分析(含数据集)
人工智能·算法·机器学习·数据挖掘·数据分析·kmeans·rapidminer
weixin_3077791318 分钟前
AWS EMR上的Spark日志实时搜索关键指标网页呈现的设计和实现
大数据·python·spark·云计算·aws
凌肖战29 分钟前
Python3 OS模块中的文件/目录方法说明十四
python
追求源于热爱!41 分钟前
记4(可训练对象+自动求导机制+波士顿房价回归预测
图像处理·人工智能·算法·机器学习·回归
深蓝海拓1 小时前
基于深度学习的视觉检测小项目(十六) 用户管理界面的组态
人工智能·python·深度学习·qt·pyqt
Qhumaing1 小时前
Python学习——函数参数详解
开发语言·python·学习
qq_433618441 小时前
哈夫曼树
数据结构·算法
Icomi_1 小时前
【PyTorch】7.自动微分模块:开启神经网络 “进化之门” 的魔法钥匙
c语言·c++·人工智能·pytorch·python·机器学习·计算机视觉
余辉zmh1 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(二)
c++·算法·leetcode·贪心算法
余辉zmh2 小时前
【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(一)
c++·算法·leetcode·贪心算法