80. Spiral Matrix
[Medium] “Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order."
Python3:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
res = []
height = len(matrix)
width = len(matrix[0])
right = width - 1
bottom = height - 1
top = left = 0
while len(res) < (height * width):
# left to right
for i in range(left, right + 1):
res.append(matrix[top][i])
top += 1
# top to bottom
for i in range(top, bottom + 1):
res.append(matrix[i][right])
right -= 1
# right to left
for i in range(right, left - 1, -1):
res.append(matrix[bottom][i])
bottom -= 1
# bottom to top
for i in range(bottom, top - 1, -1):
res.append(matrix[i][left])
left += 1
# won't break in middle of loop
return res[:(height * width)]