"""
Problem:
https://leetcode.com/problems/spiral-matrix/description/
Solution:
https://www.youtube.com/watch?v=BJnMZNwUk1M
Description:
Given an m x n matrix, return all elements of the matrix in spiral order.
"""
from typing import List
def spiral_order(matrix: List[List[int]]) -> List[int]:
left, right = 0, len(matrix[0])
top, bottom = 0, len(matrix)
def done():
if top < bottom and left < right:
return False
return True
out = []
while not done():
for i in range(left, right):
out.append(matrix[top][i])
top += 1
for i in range(top, bottom):
out.append(matrix[i][right - 1])
right -= 1
if done():
break
for i in range(right - 1, left - 1, -1):
out.append(matrix[bottom - 1][i])
bottom -= 1
for i in range(bottom - 1, top - 1, -1):
out.append(matrix[i][left])
left += 1
return out