Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Created March 3, 2021 21:34
Show Gist options
  • Save ibeauregard/25608d1a06a043548138d21d401bb8ae to your computer and use it in GitHub Desktop.
Save ibeauregard/25608d1a06a043548138d21d401bb8ae to your computer and use it in GitHub Desktop.
The most elegant way to walk a matrix in spiral order
def spiral_order(matrix):
output = []
if matrix is None:
return output
# Copy the matrix to avoid modifying the input
matrix = [line[:] for line in matrix]
while matrix:
output.extend(matrix[0])
del matrix[0]
# Transpose the matrix, and then reverse its rows
matrix = list(zip(*matrix))[::-1]
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment