54. Spiral Matrix
Medium
3698657Add to ListShare
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 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]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
很简单的模拟题
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
n = len(matrix)
m = len(matrix[0])
i = 0
total = n * m
while total:
x = y = i
result.append(matrix[x][y])
total -= 1
while total and y + 1 < m - i:
# 还能往右
y += 1
total -= 1
result.append(matrix[x][y])
while total and x + 1 < n - i:
# 还能往下
x += 1
total -= 1
result.append(matrix[x][y])
while total and y - 1 >= i:
# 还能往左
y -= 1
total -= 1
result.append(matrix[x][y])
while total and x - 1 > i:
# 还能往上
x -= 1
total -= 1
result.append(matrix[x][y])
i += 1
return result