Skip to content

Instantly share code, notes, and snippets.

@zsrinivas
Created February 13, 2015 16:22
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 zsrinivas/43051e411492b7f34980 to your computer and use it in GitHub Desktop.
Save zsrinivas/43051e411492b7f34980 to your computer and use it in GitHub Desktop.
Spiral Order
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# pylint: disable=C0111
'''input
3 3
1 2 3
4 5 6
7 8 9
'''
def spiral(n, m, mat):
nt = (1, 1, 0)
while True:
x, y, st = nt
if mat[x][y] is None:
return
print mat[x][y],
mat[x][y] = None
if st == 0:
if mat[x][y + 1] is None:
nt = (x + 1, y, 1)
else:
nt = (x, y + 1, 0)
elif st == 1:
if mat[x + 1][y] is None:
nt = (x, y - 1, 2)
else:
nt = (x + 1, y, 1)
elif st == 2:
if mat[x][y - 1] is None:
nt = (x - 1, y, 3)
else:
nt = (x, y - 1, 2)
else:
if mat[x - 1][y] is None:
nt = (x, y + 1, 0)
else:
nt = (x - 1, y, 3)
def main():
n, m = map(int, raw_input().split())
mat = [[None]*(m + 2)]
for _ in xrange(n):
mat.append([None])
mat[-1].extend(map(int, raw_input().split()))
mat[-1].append(None)
mat.append([None]*(m + 2))
spiral(n, m, mat)
# print mat
# for x in xrange(1, n + 1):
# for y in xrange(1, n + 1):
# print mat[x][y]
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment