题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
#coding:utf-8 # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param matrix int整型二维数组 # @return int整型一维数组 # class Solution: def spiralOrder(self , matrix ): # write code here if matrix == []: return [] res = [] left = 0 top = 0 bottom = len(matrix) - 1 right = len(matrix[0]) - 1 while len(res) < (len(matrix) * len(matrix[0])): for j in range(left, right + 1): res.append(matrix[top][j]) top += 1 for i in range(top, bottom + 1): res.append(matrix[i][right]) right -= 1 for j in range(right, left - 1, -1): if top - 1 == bottom: break res.append(matrix[bottom][j]) bottom -= 1 for i in range(bottom, top - 1, -1): if left - 1 == right: break res.append(matrix[i][left]) left += 1 return res
设置上下左右四个边界,后面两次需要增加上下和左右是否相等的判断(否则会重复)。开头增加特殊情况判断。