leetcode--54--螺旋矩阵

螺旋矩阵遍历算法
本文详细解析了螺旋矩阵遍历算法的实现,通过两种方法展示了如何按照顺时针螺旋顺序返回矩阵中的所有元素,适用于不同大小的矩阵。

题目描述:

  给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 1:

输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]

示例 2:

输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]


解题思路1:

  对于这个列表矩阵,先输出第一行并将其pop除去,然后将矩阵逆时针旋转90度,继续输出第一行并将其pop出去,递归的执行上述操作直至矩阵为空


代码1:

对于矩阵 matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
执行第一遍 matrix.pop(0), 输出 [1, 2, 3]
执行第二遍 matrix.pop(0), 输出 [4, 5, 6]
执行第三遍 matrix.pop(0), 输出 [7, 8, 9]

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
    ]
ret = []
while matrix:
    ret.extend(matrix.pop(0))
    print(ret)

结果为:

[1, 2, 3]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

方法1:

class Solution:
    def spiralOrder(self, matrix):
        res = []
        while matrix:
            res += matrix.pop(0)
            matrix = list(map(list, zip(*matrix)))[::-1]
        return res

s = Solution()
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
    ]
r = s.spiralOrder(matrix)
print(r)

方法2:

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        ret = []

        while matrix:
            ret.extend(matrix.pop(0))
            # matrix = map(list, zip(*matrix))[::-1] 逆时针旋转90度的极简做法
            if not matrix or not matrix[0]:
                break
            matrix2 = []
            # 将矩阵先按列组合,然后再左右翻转
            for i in range(len(matrix[0])):
                matrix2.append([])
            for j, ls in enumerate(matrix):
                for k, item in enumerate(ls):
                    matrix2[k].append(item)
            matrix = matrix2[::-1]

        return ret

s = Solution()
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
    ]
r = s.spiralOrder(matrix)
print(r)

结果为: [1, 2, 3, 6, 9, 8, 7, 4, 5]


参考链接:

Python中的map()函数与lambda()函数
python中的extend功能及用法
LeetCode-54、螺旋矩阵-中等

题目链接:https://leetcode-cn.com/problems/spiral-matrix

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值