N Queen Problem Using Backtracking

If you love playing chess, you’ll enjoy learning about the N-queens problem. It is a good problem to understand backtracking.

What is Backtracking?

In backtracking, we start with one pos­si­ble move out of many avail­able moves. We then try to solve the prob­lem.

If we are able to solve the prob­lem with the selected move then we will print the solu­tion. Else we will back­track and select some other move and try to solve it.

If none of the moves works out we claim that there is no solu­tion for the problem.

What is the N-Queens 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

Queen Solution

But how do we get this arrangement?

#data structure and algorithms #c++ #java #cplusplus #programming-c

N-Queens problem using backtracking in Java/C++
10.40 GEEK