[leetcode] 54. Spiral Matrix @ python

本文详细解析了两种矩阵螺旋遍历算法,一种是通过逐层提取元素的方式,另一种是设定方向进行遍历,同时提供了Python代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input:
[
[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]

解法1

按行或者按列从matrix中提取数字并将数字放入res中, 每次放入之前要检查matrix是否为空或者行数是否为0.

代码

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        res = []
        while matrix:
            # add the first row
            res += matrix.pop(0)
            
            # add the right-most col
            if matrix and matrix[0]:
                for row in matrix:
                    res.append(row.pop())
            # add the bottom row from right to left            
            if matrix:
                res += matrix.pop()[::-1]
                
            # add the left-most col from bottom to up
            if matrix and matrix[0]:
                res += [row.pop(0) for row in matrix][::-1]
                
        return res

解法2

设定4个方向: 右/下/左/上, 初始化x,y坐标和方向, 将matrix的值依次放入ans里, 并将已读取过的值设为’#’.

代码

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        if not matrix: return []
        directions = [(0,1),(1,0),(0,-1),(-1,0)]
        index = 0
        ans = []
        x,y = 0, 0
        m, n = len(matrix), len(matrix[0])
        
        for i in range(m*n):
            ans.append(matrix[x][y])
            matrix[x][y] = '#'
            dx, dy = directions[index][0],directions[index][1]
            if 0 <= x+dx < m and 0<= y+dy < n and matrix[x+dx][y+dy] != "#":
                x = x+dx
                y = y+dy
            else:
                index = (index+1)%4
                dx, dy = directions[index][0],directions[index][1]
                x = x+dx
                y = y+dy               
               
                
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值