Skip to content

Instantly share code, notes, and snippets.

@inside-code-yt
Created December 26, 2022 11:55
Show Gist options
  • Save inside-code-yt/087cf59c72e6874015deca60a50945db to your computer and use it in GitHub Desktop.
Save inside-code-yt/087cf59c72e6874015deca60a50945db to your computer and use it in GitHub Desktop.
class Solution:
def spiralOrder(self, matrix):
n, m = len(matrix), len(matrix[0])
i, j = 0, 0
delta = (0, 1)
direction_map = {(0, 1): (1, 0), (1, 0): (0, -1), (0, -1): (-1, 0), (-1, 0): (0, 1)}
spiral = [matrix[i][j]]
matrix[i][j] = None
while len(spiral) < n*m:
next_i, next_j = i+delta[0], j+delta[1]
if next_i < 0 or next_i == n or next_j < 0 or next_j == m or matrix[next_i][next_j] is None:
delta = direction_map[delta]
else:
i, j = next_i, next_j
spiral.append(matrix[i][j])
matrix[i][j] = None
return spiral
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment