Skip to content

Instantly share code, notes, and snippets.

@domluna
Created October 18, 2014 18:04
Show Gist options
  • Select an option

  • Save domluna/881117e774258823c984 to your computer and use it in GitHub Desktop.

Select an option

Save domluna/881117e774258823c984 to your computer and use it in GitHub Desktop.
Matrix spiral print
def spiral(M):
"""
Given a matrix M (mxn) print out the elements in spiral order
Ex:
30 42 30 55 31
21 30 60 24 38
11 22 33 44 55
prints:
30 42 30 55 31 38 55 44 33 22 11 21 30 60 24
"""
m = len(M)
n = len(M[0])
total_elements = m * n
s = 0 # top boundary of the matrix
e = m-1 # bot boundary of the matrix
l = 0
r = n-1
elems = []
# bulk of the body
while True:
# print s, e, l, r
# top row right
for j in xrange(s, r):
elems.append(M[s][j])
if len(elems) >= total_elements:
break
# right col up
for i in xrange(s, e+1):
elems.append(M[i][r])
if len(elems) >= total_elements:
break
# bot row left
for j in xrange(r-1, l, -1):
elems.append(M[e][j])
if len(elems) >= total_elements:
break
# left col down
for i in xrange(e, s, -1):
elems.append(M[i][l])
if len(elems) >= total_elements:
break
s += 1
e -= 1
l += 1
r -= 1
return elems
M1 = [[30, 42, 30, 55, 31],
[21, 30, 60, 24, 38],
[11, 22, 33, 44, 55],]
M2 = [[1,2,3,4,5],
[16,17,18,19,6],
[15, 24, 25, 20, 7],
[14, 23, 22, 21, 8],
[13, 12, 11, 10, 9]]
M3 = [[1,2,3,4,5]]
M4 = [[1,2,3,4,5],
[10, 9, 8, 7, 6]]
M5 = [[1,2],
[10,3],
[9, 4],
[8, 5],
[7, 6]]
A1 = [30, 42, 30, 55, 31, 38, 55, 44, 33, 22, 11, 21, 30, 60 ,24]
A2 = [i for i in range(1, 26)]
A3 = [1,2,3,4,5]
A4 = [i for i in range(1, 11)]
A5= [i for i in range(1, 11)]
assert(spiral(M1) == A1)
assert(spiral(M2) == A2)
assert(spiral(M3) == A3)
assert(spiral(M4) == A4)
assert(spiral(M5) == A5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment