- Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[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]
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0:
return []
res = []
m = len(matrix)
n = len(matrix[0])
total = 0
step = 0
cur = (0, -1)
flag = (0, 1)
while total < (len(matrix) * len(matrix[0])):
while True:
step += 1
total += 1
cur = (cur[0]+flag[0], cur[1]+flag[1])
res.append(matrix[cur[0]][cur[1]])
if total >= (len(matrix) * len(matrix[0])):
break
if step == n:
flag = (1, 0)
elif step == (n+m-1):
flag = (0, -1)
elif step == (n+m-1+n-1):
flag = (-1, 0)
elif step == (n+m-1+n-1+m-2):
flag = (0, 1)
break
m -= 2
n -= 2
step = 0
return res