Skip to content

Instantly share code, notes, and snippets.

@rainiera
Last active December 1, 2016 17:53
Show Gist options
  • Save rainiera/9028cdab50cd36940fbc2a0e1a25c355 to your computer and use it in GitHub Desktop.
Save rainiera/9028cdab50cd36940fbc2a0e1a25c355 to your computer and use it in GitHub Desktop.
spiral.py
def spiral(M, num_rows, num_cols):
new_order = []
# Corner indices of submatrices
top = left = 0
bottom, right = num_rows - 1, num_cols - 1
while top <= bottom and left <= right:
# Since you're sticking to one row/col, it's sufficient to use one iterator var
for i in range(left, right + 1):
new_order.append(M[top][i])
top += 1
for i in range(top, bottom + 1):
new_order.append(M[i][right])
right -= 1
for i in range(right, left - 1, -1):
new_order.append(M[bottom][i])
bottom -= 1
for i in range(bottom, top - 1, -1):
new_order.append(M[i][left])
left += 1
return ' '.join(map(str, new_order))
if __name__ == "__main__":
num_rows, num_cols = map(int, raw_input().strip().split(' '))
M = []
for _ in range(num_rows):
M.append(map(int, raw_input().strip().split(' ')))
print spiral(M, num_rows, num_cols)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment