Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

54. Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:

1
2
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

1
2
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

順時針旋轉走訪矩陣。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
outputs = []
try:
while True:
outputs += matrix.pop(0) # pop first array
print(matrix, outputs)
outputs += [item.pop(-1) for item in matrix] # pop last in each array
print(matrix, outputs)
outputs += matrix.pop(-1)[::-1] # reverse pop last array
print(matrix, outputs)
outputs += [item.pop(0) for item in matrix] [::-1]# pop last array
print(matrix, outputs)
except IndexError:
pass
return outputs

另一個不錯的解


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels