Skip to content

Instantly share code, notes, and snippets.

@ysinjab
Created November 23, 2022 08:20
Show Gist options
  • Save ysinjab/fc120677aae6eac565ef22326b47d967 to your computer and use it in GitHub Desktop.
Save ysinjab/fc120677aae6eac565ef22326b47d967 to your computer and use it in GitHub Desktop.
54. Spiral Matrix
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
i, j = 0, 0
left, right, down, up = False, True, False, False
n, m = len(matrix), len(matrix[0])
res = []
visited = set()
def is_wall(i, j):
if i >= n or i < 0 or j >= m or j <0:
return True
if (i, j) in visited:
return True
return False
for _ in range(n*m):
if right:
if not is_wall(i, j):
res.append(matrix[i][j])
visited.add((i, j))
if is_wall(i, j+1):
right = False
down = True if is_wall(i-1, j) else False
up = not down
i = i + 1 if down else i - 1
else:
j += 1
if left:
if not is_wall(i, j):
res.append(matrix[i][j])
visited.add((i, j))
if is_wall(i, j-1):
left = False
down = True if is_wall(i-1, j) else False
up = not down
i = i + 1 if down else i - 1
else:
j -= 1
if up:
if not is_wall(i, j):
res.append(matrix[i][j])
visited.add((i, j))
if is_wall(i-1, j):
up = False
right = True if is_wall(i, j-1) else False
left = not right
j = j + 1 if right else j - 1
else:
i -= 1
if down:
if not is_wall(i, j):
res.append(matrix[i][j])
visited.add((i, j))
if is_wall(i+1, j):
down = False
right = True if is_wall(i, j-1) else False
left = not right
j = j + 1 if right else j - 1
else:
i += 1
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment