Created
December 26, 2022 11:55
-
-
Save inside-code-yt/087cf59c72e6874015deca60a50945db to your computer and use it in GitHub Desktop.
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
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