MCPcopy Create free account
hub / github.com/BeeBombshell/Python-DSA / knights_tour

Function knights_tour

Backtracking/Knights_tour.py:1–21  ·  view source on GitHub ↗
(n, row, col)

Source from the content-addressed store, hash-verified

1def knights_tour(n, row, col):
2 visited = [[False]*n for i in range(n)]
3 res = []
4 def path_gen(path,r,c,visited,step):
5 if r < 0 or c < 0 or r >= n or c >= n or visited[r][c]:
6 return
7 if step == n*n:
8 res.append(path + f'({r},{c})')
9 return
10 visited[r][c] = True
11 path_gen(path + f'({r},{c}) ', r - 2, c + 1, visited, step+1)
12 path_gen(path + f'({r},{c}) ', r - 2, c - 1, visited, step+1)
13 path_gen(path + f'({r},{c}) ', r - 1, c + 2, visited, step+1)
14 path_gen(path + f'({r},{c}) ', r - 1, c - 2, visited, step+1)
15 path_gen(path + f'({r},{c}) ', r + 2, c + 1, visited, step+1)
16 path_gen(path + f'({r},{c}) ', r + 2, c - 1, visited, step+1)
17 path_gen(path + f'({r},{c}) ', r + 1, c + 2, visited, step+1)
18 path_gen(path + f'({r},{c}) ', r + 1, c - 2, visited, step+1)
19 visited[r][c] = False
20 path_gen('', row, col,visited,1)
21 return res
22
23print(knights_tour(5, 2, 2))

Callers 1

Knights_tour.pyFile · 0.85

Calls 1

path_genFunction · 0.85

Tested by

no test coverage detected