Algorithm NQueens ( k, n) //Prints all Solution to the n-queens problem
{
for i := 1 to n do
{
if Place (k, i) then
{
x[k] := i;
if ( k = n) then write ( x [1 : n]
else NQueens ( k+1, n);
}
}
}
Algorithm Place (k, i)
{
for j := 1 to k-1 do
if (( x[ j ] = // in the same column
or (Abs( x [ j ] - i) =Abs ( j – k ))) // or in the same diagonal
then return false;
return true;
}
The above code is for solving N Queens problem using backtracking.I think that it can place the first 2 queens of two rows in respective columns and then when it comes to 3rd row queen it can't be placed as no queen needs to be attacking and it will simply exit from Algorithm N queens...So how is this algorithm implements backtracking?
The eight queens problem is the problem of placing eight queens on an 8×8 chessboard such that none of them attack one another (no two are in the same row, column, or diagonal). More generally, the n queens problem places n queens on an n×n chessboard. There are different solutions for the problem.
This is the most well-known algorithm for solving N-Queen problem. The time complexity is O(n^2) because we are selecting if we can put or not put a Queen at that place. The space is the board size times the result.
The N-queen problem is used in many practical solutions like parallel memory storage schemes, VLSI testing, traffic control and deadlock prevention. This problem is also used to find out solutions to more practical problems which requires permutation like travelling salesman problem.
To solve this problem, we will make use of the Backtracking algorithm. The backtracking algorithm, in general checks all possible configurations and test whether the required result is obtained or not. For thr given problem, we will explore all possible positions the queens can be relatively placed at.
The secret here is the recursion.
Let each level of indentation below indicate a level of recursion.
(not what will actually happen, as the third queen can easily be placed, but it just would've taken quite a bit more writing and/or thinking to get to a case that will actually fail)
try to place first queen
success
try to place second queen
success
try to place third queen
fail
try to place second queen in another position
success
try to place third queen
success
try to place fourth queen
Something more in line with what the code actually does: (still not what will actually happen)
first queen
i = 1
Can place? Yes. Cool, recurse.
second queen
i = 1
Can place? No.
i = 2
Can place? No.
i = 3
Can place? Yes. Cool, recurse.
third queen
i = 1
Can place? No.
i = 2
Can place? No.
... (can be placed at no position)
fail
back to second queen
i = 4
Can place? Yes. Cool, recurse.
third queen
i = 1
Can place? No.
...
I hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With