N Queen Problem Using Backtracking Algorithm
Given a chess board of size n*n find all the place n queens so that they don’t attach each other.
Attach Conditions, Queen at (i,j) and (x,y)
- i == x (for same row)
- j == y (for same column)
- |i-x| == |j -y| (for same diagonal)
Solution:
- Same as {@link GraphColoring} with the help of backtracking
Algorithm:
- Base case: check all queen based or not
- If all queens placed then
return true
- Iterate all rows (i) one by one
- Iterate all cols (j) one by one
- If safe place queen in cell (i,j) then
- reserve cell (i, j) for this queue
- recursively call this method to place next queen
- If next queen also placed properly then
return true
- Else
- reset reserved cell (i, j)
- If safe place queen in cell (i,j) then
- Iterate all cols (j) one by one
return false
Latest Source Code:
Github: NQueenProblem.java
Output:
Queen - Position 0 (0,2) 1 (1,0) 2 (2,3) 3 (3,1)