Created
March 3, 2021 21:34
-
-
Save ibeauregard/25608d1a06a043548138d21d401bb8ae to your computer and use it in GitHub Desktop.
The most elegant way to walk a matrix in spiral order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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