剑指Offer29-顺时针打印矩阵

剑指Offer29-顺时针打印矩阵

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

示例 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]

限制:


0 <= matrix.length <= 100

0 <= matrix[i].length <= 100

来源:力扣(LeetCode)

链接:力扣

一解

利用四个边界(上下左右)控制范围,进行顺时针遍历:


class Solution:

    def spiralOrder(self, matrix):

        if not matrix: return []

        top, left, right, bottom = 0, 0, len(matrix[0]),len(matrix)

        result = [] 

        while True:

            for i in range(left, right):

                result.append(matrix[top][i])

            top += 1

            if top == bottom:

                break

            for i in range(top, bottom):

                result.append(matrix[i][right - 1])

            right -= 1

            if right == left:

                break

            for i in range(right - 1, left - 1, -1):

                result.append(matrix[bottom - 1][i])

            bottom -= 1

            if bottom == top:

                break

            for i in range(bottom - 1, top - 1, -1):

                result.append(matrix[i][left])

            left += 1

            if left == right:

                break

        return result

def spiral_order(matrix):
    top, bottom, left, right = 0, len(matrix), 0, len(matrix[0])
    direction = 0  # 0右,1下,2左,3上
    result = []
    while len(result) < len(matrix) * len(matrix[0]):
        if direction % 4 == 0:
            for i in range(left, right):
                result.append(matrix[top][i])
            top += 1
        elif direction % 4 == 1:
            for i in range(top, bottom):
                result.append(matrix[i][right - 1])
            right -= 1
        elif direction % 4 == 2:
            for i in range(right - 1, left - 1, -1):
                result.append(matrix[bottom - 1][i])
            bottom -= 1
        else:
            for i in range(bottom - 1, top - 1, -1):
                result.append(matrix[i][left])
            left += 1
        direction += 1
    return result