Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode 54 - spiral matrix - study code - provided by the peer - python code
def spiral_copy(inputMatrix):
size = len(inputMatrix) * len(inputMatrix[0])
results = []
layer = 0
while len(results) < size:
traverse_right(inputMatrix, layer, results)
if len(results) >= size:
return results
traverse_down(inputMatrix, layer, results)
if len(results) >= size:
return results
traverse_left(inputMatrix, layer, results)
if len(results) >= size:
return results
traverse_up(inputMatrix, layer, results)
if len(results) >= size:
return results
layer += 1
return results
def traverse_right(matrix, layer, results):
for c in range(layer, len(matrix[layer]) - layer):
results.append(matrix[layer][c])
def traverse_down(matrix, layer, results):
size = len(matrix)
c = len(matrix[0]) - 1 - layer
for r in range(layer + 1, size - layer):
results.append(matrix[r][c])
def traverse_left(matrix, layer, results):
size = len(matrix) - 1
r = size - layer
for c in reversed(range(layer, len(matrix[0]) - (layer + 1))):
results.append(matrix[r][c])
def traverse_up(matrix, layer, results):
size = len(matrix)
c = layer
for r in reversed(range(layer + 1, size - (layer + 1))):
results.append(matrix[r][c])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment