Skip to content

Instantly share code, notes, and snippets.

@otykhonruk
Last active March 9, 2019 23:14
Show Gist options
  • Save otykhonruk/47d9cd06ccf9c1f5db120adcaf1fb307 to your computer and use it in GitHub Desktop.
Save otykhonruk/47d9cd06ccf9c1f5db120adcaf1fb307 to your computer and use it in GitHub Desktop.
def spiral(m, n):
""" Spiral matrix traversal (counterclockwise). """
m -= 1
dx, dy = 0, 1
x, y = 0, -1
while m >= 0 and n >= 0:
for _ in range(m if dx else n):
x += dx
y += dy
yield x, y
m -= abs(dx)
n -= abs(dy)
dx, dy = dy, -dx
try:
import pytest
@pytest.mark.parametrize('m,n', [
(1, 1),
(3, 3),
(4, 4),
(4, 5),
(5, 4),
(9, 1),
(1, 9),
])
def test_spiral(m, n):
res = list(spiral(m, n))
assert len(res) == m * n
assert len(set(res)) == len(res)
for x, y in res:
assert 0 <= x < m and 0 <= y < n
except ImportError:
pass
if __name__ == '__main__':
import sys
assert len(sys.argv) > 1, 'Usage: visit.py MxN'
d = map(int, sys.argv[1].split('x'))
for p in spiral(*d):
print('{}, {}'.format(*p))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment