LeetCode:54. 螺旋矩陣
阿新 • • 發佈:2018-12-04
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