leetcode 54 螺旋矩陣

2021-10-03 07:43:58 字數 2570 閱讀 5425

題目描述:

給定乙個包含 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]

解題思路1:

對於這個列表矩陣,先輸出第一行並將其pop除去,然後將矩陣逆時針旋轉90度,繼續輸出第一行並將其pop出去,遞迴的執行上述操作直至矩陣為空

**1:

對於矩陣matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

執行第一遍matrix.pop(0), 輸出[1, 2, 3]

執行第二遍matrix.pop(0), 輸出[4, 5, 6]

執行第三遍matrix.pop(0), 輸出[7, 8, 9]

matrix =[[

1,2,

3],[

4,5,

6],[

7,8,

9]]ret =

while matrix:

ret.extend(matrix.pop(0)

)print

(ret)

結果為:

[1,

2,3]

[1,2

,3,4

,5,6

][1,

2,3,

4,5,

6,7,

8,9]

方法1:

class

solution

:def

spiralorder

(self, matrix)

: res =

while matrix:

res += matrix.pop(0)

matrix =

list

(map

(list

,zip

(*matrix)))

[::-

1]return res

s = solution(

)matrix =[[

1,2,

3],[

4,5,

6],[

7,8,

9]]r = s.spiralorder(matrix)

print

(r)

方法2:

class

solution

(object):

defspiralorder

(self, matrix)

:"""

:type matrix: list[list[int]]

:rtype: list[int]

"""ret =

while matrix:

ret.extend(matrix.pop(0)

)# matrix = map(list, zip(*matrix))[::-1] 逆時針旋轉90度的極簡做法

ifnot matrix or

not matrix[0]

:break

matrix2 =

# 將矩陣先按列組合,然後再左右翻轉

for i in

range

(len

(matrix[0]

)):[

])for j, ls in

enumerate

(matrix)

:for k, item in

enumerate

(ls)

: matrix2[k]

matrix = matrix2[::

-1]return ret

s = solution(

)matrix =[[

1,2,

3],[

4,5,

6],[

7,8,

9]]r = s.spiralorder(matrix)

print

(r)

結果為:[1, 2, 3, 6, 9, 8, 7, 4, 5]

python中的map()函式與lambda()函式

python中的extend功能及用法

leetcode-54、螺旋矩陣-中等

LeetCode 54 螺旋矩陣

給定乙個包含 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...

leetcode54 螺旋矩陣

給定乙個包含 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...

leetcode 54 螺旋矩陣

給定乙個包含 m x n 個元素的矩陣 m 行,n 列 請按照順時針螺旋順序,返回矩陣中的所有元素。示例 1 輸入 1,2,3 4,5,6 7,8,9 輸出 1,2,3,6,9,8,7,4,5 思路是 方向陣列 邊界調整 如下 class solution void matain int x,int...