Skip to content

Instantly share code, notes, and snippets.

@rsha256
Created March 10, 2021 18:56
Show Gist options
  • Save rsha256/c60d25ae6f4ba4aceb94ea39842fd354 to your computer and use it in GitHub Desktop.
Save rsha256/c60d25ae6f4ba4aceb94ea39842fd354 to your computer and use it in GitHub Desktop.
Prints a spiral ordering of a 2d matrix in O(N) time and O(1) space.
def spiralOrder(matrix):
"""
>>> spiralOrder([[1,2,3],[4,5,6],[7,8,9]])
1
2
3
6
9
8
7
4
5
"""
def spiral_coords(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield r1, c
for r in range(r1 + 1, r2 + 1):
yield r, c2
if r1 < r2 and c1 < c2:
for c in range(c2 - 1, c1, -1):
yield r2, c
for r in range(r2, r1, -1):
yield r, c1
if not matrix:
return
r1, r2 = 0, len(matrix) - 1
c1, c2 = 0, len(matrix[0]) - 1
while r1 <= r2 and c1 <= c2:
for r, c in spiral_coords(r1, c1, r2, c2):
print(matrix[r][c])
r1 += 1; r2 -= 1
c1 += 1; c2 -= 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment