Skip to content
Advertisement

Error in N Queens Problem using Backtracking and Recursion

I first implemented a zero matrix indicating that all the positions of the chessboard are initially available

JavaScript

and then I implemented three functions to fill the restrictedIndices

JavaScript

and then the recursive function

JavaScript

I am getting wrong output and I would kindly like to know if we can solve the problem this way and if there is a better alternative. I hope I could understand how recursion and Backtracking works through the solution

Advertisement

Answer

This will not work, because of the following issues:

  • answer is never populated: it can therefore be nothing else than its initial value, an empty list
  • Although you let dp return -1 when a solution is found, this value is never checked by the caller. So the caller does not know about it and goes to the next iteration of its for loop
  • When the recursive call of dp returns, the restrictedIndices list is not returned to its previous state. This means that in the next iterations of the for loop the condition [row][i]==1 will always be True — this cell was set to 1 during the first iteration. You should make sure that each iteration of the for loop starts with the exact same state of restrictedIndices.

I will not post a working solution, as this is extensively documented on the internet, and recursive solutions for Python can be found also on Stack Overflow:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement