Backtracking
Backtracking
B1 G1
B2
B2 G1 B1 B1 B2
G1
G1 G1 B2 B1
Apply constraint/bounding
function
Solution = 4 ways.
BACKTRACKING
Backtracking problems and solutions.
1) N Queens problem
Given an n x n chess board, arrange n queens on the board such that none of the queens is under attack. (Any 2
queens are under attack if both lie on the same row, column or diagonal).
Solution
A standard chessboard has 8 rows and columns but we will use 4x4 for illustration purposes.(n = 4)
Queens = Q1, Q2, Q3, Q4
Constraints – No 2 queens should appear on same row, column or diagonal.
1 2 3 4
1
2
3
4
4x4 chessboard
BACKTRACKING
Solution
Using state tree diagram, we can obtain the solutions to the problem. (We will demonstrate only the diagonal
constraint on the tree).
Q1 = 1
Q2 = 2
Q2 = 3
Q3 = 2 Q3 = 4
1 2 3 4
1 Q1 Q1 Q1 Q1
2 Q2 Q2 Q2 Q2
3 Q3 Q3
Q1 = 1
Q2 = 2 Q2 = 4
Q2 = 3
Q3 = 2 Q3 = 4 Q3 = 2
Q4 = 3
1 2 3 4
1 Q1 Q1 Q1 Q1
2 Q2 Q2 Q2 Q2
3 Q3 Q3 Q3
4 Q4
Q1 = 1 Q1 = 2
Q2 = 2 Q2 = 4 Q2 = 4
Q2 = 3
Q3 = 2 Q3 = 4 Q3 = 2 Q3 = 1
Q4 = 3 Q4 = 3
1 2 3 4
1 Q1 Q1 Q1 Q1
2 Q2 Q2 Q2 Q2
3 Q3 Q3
4 Q4
Moving Q1 to (1,2) Q2 can then be placed Q3 can then be placed at Q4 can then be placed at
at (2,4) (3,1) (4,3)
BACKTRACKING
Solution
1 2 3 4
1 Q1
2 Q2
3 Q3
4 Q4
This is one of the solutions to the problem. The other solution will be the mirror image of the board. You can extend
the state tree even further to see if its correct.
1 2 3 4
1 Q1
2 Q2
3 Q3
4 Q4
You can apply the same procedure for an 8x8 chess board.
BACKTRACKING
Algorithm
START
1. begin from the leftmost column
2. if all the queens are placed,
return true/ print configuration
3. check for all rows in the current column
a) if queen placed safely, mark row and column; and
recursively check if we approach in the current
configuration, do we obtain a solution or not
b) if placing yields a solution, return true
c) if placing does not yield a solution, unmark and
try other rows
4. if all rows tried and solution not obtained, return
false and backtrack
END
BACKTRACKING
Implementation
backtrackingjava.txt
backtrackingerlang.txt
Solution.
This problem can be solved using backtracking.
n = 6. m = 30.
We can solve for the solutions using a states tree diagram.
BACKTRACKING
0, 73
Solution.
X1 = 1
{5, 10, 12, 13, 15, 18}.
5, 68
X2 = 1
15, 58
X3 = 1 X3 = 0
27, 46 15, 46
X4 = 1 X4 = 1 X4 = 0
X4 = 0
28, 33
40, 33 27, 33 15, 33
X5 = 1 X5 = 0
X5 = 1 X5 = 1
X5 = 0
43, 18 28, 18
42, 18 27, 18 30, 18
X6 = 1 X6 = 1
X6 = 0 X6 = 0
1 1 0 0 1 0 Is one of the solutions. i.e {5, 10, 15}. Extend the state tree to find other solutions.
BACKTRACKING
2) Sum of Subsets Problem.
Algorithm
void subset_sum(int list[], int sum, int starting_index, int target_sum)
{
if( target_sum == sum )
{
subset_count++;
if(starting_index < list.length)
subset_sum(list, sum - list[starting_index-1], starting_index, target_sum);
}
else
{
for( int i = starting_index; i < list.length; i++ )
{
subset_sum(list, sum + list[i], i + 1, target_sum);
}
}
}