Below is my attempt at solving the 8 queens problem to print one solution. (place 8 queens on a chessboard such that none of them are attacking each other). However, this solution only places 6 queens. I need another opinion of where I am making a mistake. I'm doing this in more of a BFS style instead of backtracking.
solving the eight queens to produce a solution
237 views Asked by user3050784 At
1
It seems your algorithm is malfunctioning at some point. Upon running it, I found the following issues:
You are constantly setting
visited[i][j]
to 0 in your for loop in main. This always resets visited to 0 even if a recursion call is made. In fact, when you declare bothvisited
andboard
they are initiated to arrays full of 0s. So you can get rid of both set statements in there. In addition, because you reset the arrays, your recursive function ends up setting both values to 0 and then finds them again."For debugging, in the
!hasQueen
statement, you should output theboard[row][col]
coordinates, which show you the coordinates that have been found. The final list before it prints out the grid shows that 2,4 and 1,6 are found and set twice.The actual chessboard that is output ends up with an impossible solution:
(sorry I can't get the numbers to format)
Both layout X and layout Y fail the 8 queens rules.
If you run your program with the setting to 0 commented out, you will see that it grinds to a halt after finding 6 locations.