0% found this document useful (0 votes)
3 views

Assignment 1

Uploaded by

Preeti Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Assignment 1

Uploaded by

Preeti Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Printing all solutions in N-Queen Problem

The N Queen is the problem of placing N chess queens on an N×N


chessboard so that no two queens attack each other. For example, following
is a solution for 4 Queen Problem.
The N Queen is the problem of placing N chess queens on an N×N
chessboard so that no two queens attack each other. For example, following
are two solutions for 4 Queen Problem.

Backtracking Algorithm
The idea is to place queens one by one in different columns, starting from
the leftmost column. 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.
Q

1) Start in the leftmost column


2) If all queens are placed
return true
3) Try all rows in the current column. Do following
for every tried row.
a) If the queen can be placed safely in this row
then mark this [row, column] as part of the
solution and recursively check if placing
queen here leads to a solution.
b) If placing queen in [row, column] leads to a
solution then return true.
c) If placing queen doesn't lead to a solution
then unmark this [row, column] (Backtrack)
and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked,
return false to trigger backtracking.

You might also like