LeetCode-剑指 Offer 29. 顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路1:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: return []
        l, r, t, b, res = 0, len(matrix[0]) - 1, 0, len(matrix) - 1, []
        while True:
            for i in range(l, r+1): res.append(matrix[t][i])
            t += 1
            if t > b: break
            for i in range(t, b+1): res.append(matrix[i][r])
            r -= 1
            if l > r: break
            for i in range(r, l-1, -1): res.append(matrix[b][i])
            b -= 1
            if t > b: break
            for i in range(b, t-1, -1): res.append(matrix[i][l])
            l += 1
            if l > r: break
        return res

具体思路链接(有点麻烦,但不难理解)

https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/

思路2:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        while matrix:
            res += matrix.pop(0)  # 将矩阵第一维的数据依次放入res中,也可以使用extend函数
            matrix = list(zip(*matrix))[::-1]  # zip函数对matrix处理,导致数据竖向读取,然后将list之后的列表[::-1],也就是第一维度翻转,造成了将matrix逆时针旋转90度的效果,可以具体代入值推理。
        return res
posted @ 2022-03-21 10:49  小Aer  阅读(4)  评论(0编辑  收藏  举报  来源