8-queen problem

Bharat Kul Ratan
1 min readDec 9, 2017

The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other.

We can start the solution by putting 8 queens in 8 columns. But if you put the queens randomly there are very high chances that they will be attacking each other and hence not the solution. So we have to just find the row for each queen such that they don’t attack among themselves.

We will start from first column and will go to eighth column one by one. For each column we will try all the 8 rows to find that row in which putting the current queen will not affect the previously put queens. If we can not find such row, we’ll backtrack to previous column and start the process again.

isSafe() takes the 2-D array, row, and column as parameters and decides if the given cell denoted by row and column is safe to put the queen. dfs() takes 2-D array and current column for which we are trying to put the queen. It will recursively iterate to next column if we find a row to put the queen in current column and it will backtrack to previous one if there is no valid row available to put the queen.

I haven’t put much efforts in the code. So if you find any bug or optimization feel free to comment it.

--

--