Maze Solving N Queens
Maze Solving N Queens
N-QUEENS PROBLEM
Introduction
The solution can be a matrix indicating the position of the queens or the index
numbers of the cells in whicb the queens have been placed
N-QUEENS PROBLEM
When we place a queen in a column, we check for clashes with already placed
queens.
In the current column, if we find a row for which there is no clash, we mark this row
and column as part of the solution.
If we do not find such a row due to clashes then we backtrack and return false.
N-QUEENS PROBLEM
Backtracking Algorithm
1) Start in the leftmost column
3) If all rows have been tried and nothing worked, return false to trigger backtracking.
N-QUEENS PROBLEM
Program
nqueens1.java
Sample IO
Input
8
Output
N-QUEENS-01
Optimization
The idea is not to check every element in right and left diagonal instead use
property of diagonals:
1. The sum of i and j is constant and unique for each right diagonal where i is
the row of element and j is the column of element.
2. The difference of i and j is constant and unique for each left diagonal
where i and j are row and column of element respectively.
N-QUEENS PROBLEM
Program
nqueens2.java
https://learn.codemithra.com