Skip to content

Instantly share code, notes, and snippets.

@codyhex
Created January 27, 2020 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyhex/cf63ff1004428a6ef8e055d6e9f4b5bd to your computer and use it in GitHub Desktop.
Save codyhex/cf63ff1004428a6ef8e055d6e9f4b5bd to your computer and use it in GitHub Desktop.
class Solution:
def spiral_print(self, matrix):
seen = set()
action_seq = [(0, +1), (+1, 0), (0, -1), (-1, 0)]
act = 0
curr = (0, 0)
seen.add(curr)
res = []
res.append(matrix[curr[0]][curr[1]])
changes = 0
while True:
if changes > 1:
# finished
return res
""" becareful of tuple + tuple, that is (tuple, tuple)
"""
next_move = (curr[0] + action_seq[act][0], curr[1] + action_seq[act][1])
if 0 <= next_move[0] < len(matrix) and 0 <= next_move[1] < len(matrix[1]) and next_move not in seen:
seen.add(next_move)
curr = next_move
changes = 0
res.append(matrix[curr[0]][curr[1]])
else:
act +=1
changes +=1
if act == len(action_seq):
act = 0
grid = [[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
print(Solution().spiral_print(grid))
# 1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment