Skip to content
Advertisement

How can I check if a diagonal element in 2D array is occupied?

I’m trying to complete the nQueens puzzle problem with a 2D array. I’m having trouble checking to see if an element diagonal to the current element is occupied? I tried doing another for loop, but it only changes the output of the next row and then the rest are the same.

Here’s my code:

JavaScript

Advertisement

Answer

The issue is with isSafe, the method was not checking the diagonal elements which is why it was merely advancing to the next diagonal because the current checks would have advanced to the next row [ fillPositions(board, r+1) ] and isSafe was just scanning the columns to the left.

Following modifications should help

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