I have a piece of Python code that implements a recursive backtracking algorithm for solving the famous N-Queens problem in chess.
def Backtrack(board, col):
if col >= N:
return True
for i in range(N):
if (ld[i - col + N - 1] != 1 and rd[i + col] != 1) and cl[i] != 1:
board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
if Backtrack(board, col + 1):
return True
board[i][col] = 0 # Backtrack
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
return False
where
ld = np.zeros(2*N - 1, dtype=int)
rd = np.zeros(2*N - 1, dtype=int)
cl = np.zeros(N, dtype=int)
board = np.zeros((N, N), dtype=int)
The Problem:
I want to keep a track of how many times the recursive backtracking algorithm is called.
My Attempt:
I added a counter variable to the code such that
def Backtrack(board, col, counter):
counter += 1
print('here', counter)
if col >= N:
return True
for i in range(N):
if (ld[i - col + N - 1] != 1 and rd[i + col] != 1) and cl[i] != 1:
board[i][col] = 1
ld[i - col + N - 1] = rd[i + col] = cl[i] = 1
if Backtrack(board, col + 1, counter):
return True
board[i][col] = 0 # Backtrack
ld[i - col + N - 1] = rd[i + col] = cl[i] = 0
return False
however for N = 4 the output is
here 1
here 2
here 3
here 3
here 4
here 2
here 3
here 4
here 5
which shows that my attempt is incorrect. The function is called 9 times but at the end the counter variable is 5.