输入一个矩阵(n*n),按照从外向里以顺时针的顺序依次打印出每一个数字。 示例 1: 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] 限制: 0 <= matrix.length 0 <= matrix[i].length
import copy class Solution(object): def __init__(self): self.lis = [] def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ rows = rols = len(matrix) if rows < 1: return [] if rows == 1: self.lis.append(matrix[0][0]) return self.lis if rows == 2: self.lis.append(matrix[0][0]) self.lis.append(matrix[0][1]) self.lis.append(matrix[1][1]) self.lis.append(matrix[1][0]) return self.lis if rows == 3: for i in matrix[0]: self.lis.append(i) for i in range(1, rols-1): self.lis.append(matrix[i][rols-1]) for i in range(rols-1, -1, -1): self.lis.append(matrix[rols-1][i]) for i in range(rols-2, 0, -1): self.lis.append(matrix[i][0]) self.lis.append(matrix[1][1]) return self.lis if rows > 3: for i in matrix[0]: self.lis.append(i) for i in range(1, rols-1): self.lis.append(matrix[i][rols-1]) for i in range(rols-1, -1, -1): self.lis.append(matrix[rols-1][i]) for i in range(rols-2, 0, -1): self.lis.append(matrix[i][0]) lic = copy.copy(matrix) lic.pop(0) lic.pop() for i in lic: i.pop(0) i.pop() self.spiralOrder(lic) return self.lis s = Solution() liy = [] lix = [] n = 3 for i in range(1, n*n+1): liy.append(i) for i in range(n): lix.append(liy[i*n : i*n + n]) ret = s.spiralOrder(lix) print(ret)
结束!