If you love playing chess, you’ll enjoy learning about the N-queens problem. It is a good problem to understand backtracking.
In backtracking, we start with one possible move out of many available moves. We then try to solve the problem.
If we are able to solve the problem with the selected move then we will print the solution. Else we will backtrack and select some other move and try to solve it.
If none of the moves works out we claim that there is no solution for the problem.
How can N queens be placed on an NxN chessboard so that no two of them attack each other?
This problem is commonly seen for N=4 and N=8.
Let’s look at an example where N=4
Before solving the problem, you need to know about the movement of the queen in chess.
A queen can move any number of steps in any direction. The only constraint is that it can’t change its direction while it’s moving.
One thing that is clear by looking at the queen’s movement is that no two queens can be in the same row or column.
That allows us to place only one queen in each row and each column.
When N=4, the solution looks like :
Queen Solution
But how do we get this arrangement?
#data structure and algorithms #c++ #java #cplusplus #programming-c