8 Queens Problem
8 Queens Problem
Problem Statement
Given an 8x8 chess board, you must place 8 queens on the
board so that no two queens attack each other. Print all
possible matrices satisfying the conditions with positions with
queens marked with '1' and empty spaces with '0'. You must
solve the 8 queens problem using backtracking.
Note 1: A queen can move vertically, horizontally and
the general
approach to solving this problem.
Sample Example
Example: One possible solution to the 8 queens problem
using backtracking is shown below. In the first row, the queen
is at E8 square, so we have to make sure no queen is in
column E and row 8 and also along its diagonals. Similarly,
for the second row, the queen is on the B7 square, thus, we
have to secure its horizontal, vertical, and diagonal squares.
The same pattern is followed for the rest of the queens.
Output:
00001000
01000000
00010000
00000010
00100000
00000001
00000100
10000000
Bruteforce Approach
Backtracking Approach
This approach rejects all further moves if the solution is
declined at any step, goes back to the previous step and
explores other options.
Algorithm
Let's go through the steps below to understand how this
algorithm of solving the 8 queens problem using backtracking
works: