1、题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
2、题解
2.1、解法一
原理:递归
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ print("matrix:",matrix) if matrix == []: return [] m,n = len(matrix),len(matrix[0]) ret = [] # 上侧,右侧 for i in range(m): if i== 0: for j in range(n): tmp = matrix[i][j] ret.append(tmp) else: if m >1 and i != m-1: tmp = matrix[i][n-1] ret.append(tmp) print("ret上:",ret) # 下侧 if m >1: l = reversed(matrix[m-1]) print(l) for i in l: ret.append(i) # 左侧 if m >2 and n>1: for i in range(m-2,0,-1): ret.append(matrix[i][0]) print("ret:",ret) # 新矩阵 new = [] for i in range(m): if i != 0 and i != m-1: tmp = [] for j in range(n): if j != 0 and j != n-1: tmp.append(matrix[i][j]) if tmp != []: new.append(tmp) print("new:",new) if new != []: r = self.spiralOrder(new) print("r:",r) ret.extend(r) return ret
2.2、解法二
原理: 取首行,去除首行后,对矩阵翻转来创建新的矩阵,再递归直到新矩阵为[],退出并将取到的数据返回
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ # 取首行,去除首行后,对矩阵翻转来创建新的矩阵, # 再递归直到新矩阵为[],退出并将取到的数据返回 ret = [] if matrix == []: return ret ret.extend(matrix[0]) # 上侧 new = [reversed(i) for i in matrix[1:]] if new == []: return ret r = self.spiralOrder([i for i in zip(*new)]) ret.extend(r) return ret