LeetCode 54. Spiral Matrix--Python解法--螺旋排序

本文解析了LeetCode上的螺旋矩阵题目,提供了两种Python实现方案,一种使用方向数组模拟螺旋移动,另一种通过边界循环实现,详细阐述了算法思路与代码实现。

题目地址:Spiral Matrix - LeetCode


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]

这道题目的意思是把矩阵螺旋的顺序排出来,但从难度来看,是毫无难度的,但写起来发现还是比较麻烦的。
Python解法如下:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: return []
        R, C = len(matrix), len(matrix[0])
        seen = [[False] * C for _ in matrix]
        ans = []
        dr = [0, 1, 0, -1]
        dc = [1, 0, -1, 0]
        r = c = di = 0
        for _ in range(R * C):
            ans.append(matrix[r][c])
            seen[r][c] = True
            cr, cc = r + dr[di], c + dc[di]
            if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:
                r, c = cr, cc
            else:
                di = (di + 1) % 4
                r, c = r + dr[di], c + dc[di]
        return ans

看到另外一个逻辑更清晰的代码:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        if len(matrix)==0:
            return res
        m = len(matrix)
        n = len(matrix[0])
        k = 0
        l = 0
        last_row = m-1
        last_col = n-1
        
        
        
        while k <= last_row and l <= last_col:
            for i in range(l,last_col+1):
                res.append(matrix[k][i])
            k += 1
            
            for i in range(k,last_row+1):
                res.append(matrix[i][last_col])
            last_col -= 1
            
            if(k<=last_row):
                for i in range(last_col,l-1,-1):
                    res.append(matrix[last_row][i])
                last_row -= 1
            
                
            if(l<=last_col):
                for i in range(last_row,k-1,-1):
                    res.append(matrix[i][l])
                l += 1
                
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值