I was attempting a recursive solution to the n queens problem. Please take a look at this code:
def solve(n,chess_arr,forbidden_cells=[]):
print("1.",n,chess_arr,forbidden_cells)
if n>(n*n)-len(forbidden_cells):
return False
elif n==1:
printchessboard(chess_arr)
return True
else:
for i in range(len(chess_arr)):
for j in range(len(chess_arr[i])):
print("2. ",n,(i,j),(i,j) not in forbidden_cells,forbidden_cells)
if (i,j) not in forbidden_cells:
chess_arr[i][j]=["Q"]
forbidden_row=i
forbidden_col=j
partial_forbidden_cells=create_partial_forbidden(n,chess_arr,forbidden_row,forbidden_col,forbidden_cells)
forbidden_cells.extend(partial_forbidden_cells)
if solve(n-1,chess_arr,forbidden_cells):
return True
else:
chess_arr[i][j]=[]
for partial in partial_forbidden_cells:
forbidden_cells.remove(partial)
return False
I am facing a conceptual doubt here. While the first print statement always returns a non empty forbidden_cells list on several occasions but the second print statement always returns an empty list. I am at a loss why this is so? Could someone please explain.
My expectation: Since I am passing the forbidden_list as a parameter, I expect it to get updated with each iteration and at each iteration, I would like to be dealing with the most recent and updated forbidden_list.
Thanks for the help!