-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.py
49 lines (37 loc) · 1.74 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution:
def knightTour(self, N):
def isSafe(x, y):#checked
# Check cell (x, y) is not OOB and value is not visited already
if 0 <= x < N and 0 <= y < N and board[x][y] == -1:
return True
return False
def backtrack(cur_x, cur_y, moveCount):
# 1) Base case: If all moves are done
if moveCount >= N*N:
return True
# 2) Breath: --> Consider all possible moves
for i in range(8):
next_x = cur_x + move_x[i]
next_y = cur_y + move_y[i]
#print("next x{} and next y{}".format(next_x, next_y))
# 3) Check if this move can be taken
if isSafe(next_x, next_y):
# 4) Take this move
board[next_x][next_y] = moveCount
# 5) Check if this move leads to a solution from all recur moves
if backtrack(next_x, next_y, moveCount+1):
return True
# 6) This move didn't work, Backtrack...
board[next_x][next_y] = -1
return False # No move from all 8 possible worked, so Backtrack previous move and re-try
# Initialize NxN chess board
board = [[-1 for i in range(N)] for j in range(N)]
# Possible moves of a knight on chess-board, X and Y coordinates
move_x = [2, 1, -1, -2, -2, -1, 1, 2]
move_y = [1, 2, 2, 1, -1, -2, -2, -1]
board[0][0] = 0 # start with the Knight is initially at the first block
backtrack(0, 0, 1) # Step counter for knight's position
return board
if __name__ == "__main__":
s = Solution()
print(s.knightTour(8))