面试题29 顺时针打印矩阵 Python3

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

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

思路 设置边界,不断循环

  • 首先设置上下左右4个边界,
  • 之后依次按照从左到右从上到下从右到左从下到上的顺时针顺序进行遍历,并将结果依次存入一个新的列表;
  • 当两个边界重合时遍历完成。

 

代码

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

        if not matrix:
            return []

        up = 0                    # 上边界
        bottom = len(matrix)-1    # 下边界
        left = 0                  # 左边界
        right = len(matrix[0])-1  # 右边界

        res = []
        while True:
            for i in range(left, right+1):          # 从左到右
                res.append(matrix[up][i])
            up = up + 1
            if up > bottom:
                break

            for i in range(up, bottom+1):           # 从上到下
                res.append(matrix[i][right])
            right = right - 1
            if right  bottom:
                break

            for i in range(bottom, up-1, -1):           # 从下到上
                res.append(matrix[i][left])
            left = left + 1
            if right 

结果

面试题29 顺时针打印矩阵 Python3_第1张图片

 

总结

边界条件,即刚开始对bottom和right的赋值,以及后面range里的的+1和-1都很容易出错。

尤其是range(a,b,-1)时,只是向前递进到b+1,不会递进到b。

你可能感兴趣的:(Leetcode)