Current section

Files

Jump to
inplace lib examples knight_tour.py
Raw

lib/examples/knight_tour.py

def knight_tour_stack(n, start=(0, 0)):
moves = [(2, 1), (1, 2), (-1, 2), (-2, 1),
(-2, -1), (-1, -2), (1, -2), (2, -1)]
def legal(r, c):
return 0 <= r < n and 0 <= c < n
stack = [(start, [start], {start})]
while stack:
(r, c), path, visited = stack.pop()
if len(visited) == n * n:
print("solution")
return path
next_moves = []
for dr, dc in moves:
nr, nc = r + dr, c + dc
if legal(nr, nc) and (nr, nc) not in visited:
next_moves.append((nr, nc))
for nxt in reversed(next_moves):
stack.append((nxt, path + [nxt], visited | {nxt}))
return None