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

相关推荐
小尧嵌入式6 小时前
QT软件开发知识流程及秒表计时器开发
开发语言·c++·qt·算法
踢球的打工仔6 小时前
前端html(3)
前端·算法·html
程序员-King.6 小时前
day114—同向双指针(数组)—统计得分小于K的子数组数目(LeetCode-2302)
算法·leetcode·双指针
智算菩萨6 小时前
深度学习在教育数据挖掘(EDM)中的方法体系:从任务建模到算法范式的理论梳理与总结
深度学习·算法·数据挖掘
_OP_CHEN6 小时前
【算法基础篇】(二十七)从记忆化搜索到动态规划:保姆级入门指南,带你吃透 DP 核心思想!
算法·蓝桥杯·动态规划·记忆化搜索·算法竞赛·acm/icpc
是Dream呀6 小时前
后端开发入门超完整速成路线(算法篇)
算法
代码雕刻家6 小时前
1.10.课设实验-数据结构-查找-机票查询
c语言·数据结构·算法
Keep_Trying_Go6 小时前
基于Transformer的目标统计方法(CounTR: Transformer-based Generalised Visual Counting)
人工智能·pytorch·python·深度学习·transformer·多模态·目标统计
biyezuopinvip7 小时前
音频DSP技术与应用数字信号处理算法实验(论文)
算法·音视频·信号处理·代码·音频dsp技术·应用数字信号·处理算法实验
追风少年ii7 小时前
脚本测试--R版本 vs python版本的harmony整合效果比较
linux·python·机器学习·空间·单细胞·培训