Skip to content

Instantly share code, notes, and snippets.

@icamys icamys/visit.py
Last active Jul 17, 2018

Embed
What would you like to do?
VIsit all cells in grid like a snail
import sys
assert len(sys.argv) == 2
width, height = sys.argv[1].split('x')
width = int(width)
height = int(height)
assert width > 0
assert height > 0
grid: list = [[0 for x in range(width)] for y in range(height)]
directions = (
'top',
'right',
'bottom',
'left',
)
directions_count = len(directions)
starting_direction_index = 2
starting_coord = dict(x=0, y=0)
current_direction_index = starting_direction_index
current_coord = starting_coord
def change_direction(direction_index: int):
return (direction_index - 1) % directions_count
def get_next_coord(coord: dict, index: int):
nxt = coord.copy()
if directions[index] == 'top':
nxt['y'] -= 1
elif directions[index] == 'right':
nxt['x'] += 1
elif directions[index] == 'bottom':
nxt['y'] += 1
elif directions[index] == 'left':
nxt['x'] -= 1
return nxt
def coord_in_grid(coord: dict):
return 0 <= coord['x'] <= width - 1 and 0 <= coord['y'] <= height - 1
def coord_is_empty(coord: dict):
return grid[coord['y']][coord['x']] == 0
can_move = True
while can_move:
print(current_coord)
grid[current_coord['y']][current_coord['x']] = 1
next_coord = get_next_coord(current_coord, current_direction_index)
if coord_in_grid(next_coord) and coord_is_empty(next_coord):
current_coord = next_coord
else:
current_direction_index = change_direction(current_direction_index)
next_coord = get_next_coord(current_coord, current_direction_index)
if coord_in_grid(next_coord) and coord_is_empty(next_coord):
current_coord = next_coord
else:
can_move = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.