Group 2
Group 2
INTERNATIONAL SCHOOL
-------------------------------
Group :2
Dam Thanh Loan 22070714
Nguyen Thi Lan Anh 22070844
Tran Thi Huong Ly 21070569
Vu Thi Thuy Nga 22070710
Table of contents
Abstract 4
List of abbreviations 5
Introduction 7
2. Objectives of project 7
I. Definition 9
1. Backtracking process 9
A. Advantages of Backtracking 12
B. Disadvantages of Backtracking 13
3. Pathfinding Problems 15
Conclusion 23
Reference 24
Member’ contribution 25
3
Abstract
The report also analyzes the diversity in the application of the algorithm, for
example in solving constraint satisfaction problems (CSP) such as Sudoku, path
finding problems, etc. The report will develop a detailed implementation of the N-
Queens problem to clearly illustrate the algorithm process of handling constraints by
permuting and backtracking when detecting conflicts.
In addition, the report also discusses the advantages of the algorithm (including
flexibility, pruning mechanism). However, the algorithm also has its own limitations
such as exponentially increasing time complexity and large memory requirements
when solving large-scale problems. However, the backtracking algorithm is still an
indispensable method in solving computational problems using hybrid techniques and
parallel computing.
4
List of Abbreviations
Abbreviation Definition
BT Backtracking
IS Initial State
C Checkpoints
TN Terminal Nodes
CSP Constraint Satisfaction Problems
5
List of figures and tables
Figure 2.1 State-space tree of solving the four queens ‘problem by backtracking 7
6
Introduction
2. Objectives of project
8
Chapter 1: Backtracking Algorithm
I. Definition
Backtracking is a general algorithm technique for finding all possible solutions for
the problem and discards partial solutions as soon as possible without following them
till the end (Pal, D & Halder, S 2018). Backtracking is a depth-first traversal of the
path in the graph where nodes are states of the solution and edge between two states of
solution only if one state can be reached from another state. Each path may lead to a
solution, taking one path at a time and as soon as the path does not lead to the solution
then go back and try with the alternate path.
In fact, in life, there are many activities where we are applying the backtracking
strategy. For instance, in the maze puzzle game, when you enter a maze, you may
encounter many turns. You try to go down one turn, and if you find it is a dead end,
you will backtrack to the nearest turn and try other directions. Eventually, you will try
all possible paths until you find the exit.
1. Backtracking process
9
Then the backtracking algorithm is performed through the following steps:
● Consider all possible values of x 1, try to let x 1 receive those values in turn. For
each test value for x 1, we will:
● Consider all possible values of x 2, try to let x 2 receive those values in turn. For
each test value for x 2, we will consider possible values of x 3 and continue like
that
● Consider all possible values of xn, try to let x n receive those values in turn.
Print out the found configuration.
However, if the algorithm encounters a dead-end, meaning all values for the
current variable are invalid, it backtracks by unassigning the most recent variable and
testing a different value for it. This systematic approach ensures that all possible
configurations are explored by exhaustively checking every potential combination
within the domain of the variables.
10
Figure 1.1 - Backtracking process
where:
IS (Initial state): is the starting point where the algorithm begins its search for a
solution.
C (Checkpoints): At each "C" node, the algorithm evaluates possible choices to extend
the current partial solution. If a choice is viable, the algorithm moves forward to the
next state in the tree.
Non-accepted Terminal Nodes (TN1, TN2, TN3, TN4, TN5): These are dead-end
nodes, where the algorithm finds that the current choices cannot form a valid solution.
Upon reaching these nodes, the algorithm backtracks to the nearest checkpoint node to
try a different path.
Accepted Terminal Node (TN6): This is the goal node, representing a solution that
satisfies all the problem’s conditions. When the algorithm reaches this node, it stops,
as it has found a valid solution.
Backtracking Process:
● We start with an empty solution, S={}. This is where the algorithm begins
searching for a solution.
11
● At each checkpoint C i, the algorithm tries assigning a value v to the next
variable x i. If this choice satisfies the problem’s constraints, it adds the
assignment to the current solution S and moves forward. S = S ∪ { x i = v} (if v
is valid for x i)
● If we reach a point where no valid values are left to assign to x i, then S is at a
dead-end (non-accepted terminal node). The algorithm will backtrack to the
previous checkpoint C i−1 and try a different value for the last variable.
● If all variables x 1 , x 2 ,... , x n have been assigned values, and these values satisfy
all constraints, we reach a valid solution, S, which is our goal.
Key Points:
A. Advantages of Backtracking:
- Flexibility: A vast array of issues can be resolved by backtracking, ranging
from straightforward riddles like the N-Queens problem to challenging
combinatorial optimization issues. It can be modified to meet different needs
and restrictions related to a particular issue.
- Pruning: By eliminating some of the search tree's branches that are unlikely to
yield a solution, backtracking can be maximized. This can shorten the search
space and expedite the time it takes to find a solution.
12
- Concurrent execution: Since each recursive call can be carried out
independently, backtracking algorithms can be parallelized and run across
several threads. This may expedite the solution time significantly.
B. Disadvantages of Backtracking:
- Time complexity: Because backtracking covers a wide search space that could
have a lot of dead ends, it can be extremely sluggish for large problems. This
may lead to a high temporal complexity, particularly if the task involves a
complex search space and a lot of restrictions.
13
Chapter 2: Application of Backtracking Algorithm
How It Works:
● Sudoku: Backtracking is used to fill a 9x9 grid of numbers, ensuring that each
number is unique within its row, column, and subgrid.
● Crossword Puzzles: As words are placed into the grid, backtracking ensures
that they fit within the available spaces and align correctly with other words.
● N-Queens Problem: The objective is to place N queens on an NxN chessboard
so that no two queens threaten each other. Backtracking systematically
explores different placements and reverts when an invalid configuration is
encountered.
14
● Graph Coloring: The task is to color the vertices of a graph so that no two
adjacent vertices share the same color. Backtracking helps in trying different
colorings and discarding those that violate the constraint.
3. Pathfinding Problems
Finding paths in a maze or grid where certain paths may be blocked, such as:
To illustrate how the backtrack algorithm works, let's consider a concrete example: the
N-Queens Problem.
1. N-Queens Problem
The N-queens problem was proposed for the first time in 1850 by famous German
mathematician and physicist Carl Gauss. Scientists from various fields had been
studying it for more than a century. It is to determine a placement of n queens on an N
× N chessboard, such that no two queens can attack each other [3]. Remember that a
15
queen can attack another if they lie on the same row or same column or on the same
diagonal in either direction. There are a number of ways these N queens can be placed
and each way is one solution. This problem can be solved by using backtracking
method. However, the huge size N-queens problem cannot be resolved by
backtracking.
The problem is is challenging because of the fact that there are ( ❑nn 2 ¿ i.e n2 Cn
possible solutions of the problem. However, since each queen must be placed in a
distinct row and column, the actual number of valid solutions is only n! [5]. Each
solution can be represented as a tuple of length N as (Q1,Q2,………QN). Index
positions of the tuple represent row positions and values represent column position.
Reverse can also be chosen. Thus solutions are basically a permutation of the tuple
(1,2,3,….N).
Suppose one queen already placed at (i, j) and another queen going to place at (m,n)
cell, then they are on the same diagonal either
m–i=n-j
or
m–i=j-n
Therefore two queens lie on the same diagonal if and only if m - i = |j - n|.
16
“How many ways are there to place four queens on a chessboard in such a way that no
queen is attacking any other?”
Backtracking Steps:
● Step 1: Initialization
Start by creating an empty chessboard of size 4x4, where all cells are marked as empty
(no queen placed).
● Step 3: Recursion
For each empty cell in the current row, try placing a queen in that cell.
After placing the queen, check if it is being attacked by any queen already placed in
previous rows (according to the queen's movement rules: row, column, and diagonal).
If the queen is not attacked, mark the cell as occupied and recursively attempt to place
a queen in the next row.
If the queen is attacked, move on to the next empty cell in the same row and try
placing the queen there.
● Step 4: Backtracking
17
If no valid position for placing a queen is found in the current row, backtrack to the
previous row and move the previously placed queen to the next possible position in
that row.
If all N queens have been successfully placed on the chessboard without any conflicts,
store this configuration as a solution and exit the recursion.
If all possibilities have been explored and no valid arrangement has been found,
backtrack to try other queen placements, ensuring that all possible solutions are
checked before ending the algorithm.
18
Figure 2.1 - State-space tree of solving the four queens‘ problem by backtracking.
In the 4-Queens problem, we place queens row by row while ensuring no two
queens threaten each other. with the empty board and then we place the first queen in
the first available column, column 1 (A[1] = 1). For the second row, the queen is
placed in column 3, the first position that does not conflict with the first queen (A[2] =
3). In the third row, we find that there's no safe column to place a queen without
conflicting with the queens already on the board. It reaches a dead end, because it is
impossible to place the queen in the 3rd row.
19
Figure 2.2 - A deadlock situation of non-attacking 4-queen problem
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 4
// Non-Attacking-Queen algorithm
void Non_Attacking_Queen(int ROW) {
for (int COL = 1; COL <= N; COL++) {
if (PLACE(ROW, COL)) {
A[ROW] = COL; // Place the queen
if (ROW == N) {
displayBoard(); // Display the board
configuration if all queens are placed
} else {
Non_Attacking_Queen(ROW + 1); // Try to place
queen in the next row
}
}
}
}
int main() {
// Initialize the positions of queens to zero
for (int i = 0; i <= N; i++) {
A[i] = 0;
}
return 0;
}
Output:
. Q . .
. . . Q
Q. . .
. . Q .
. . Q .
Q. . .
. . . Q
21
. Q . .
Time Complexity
The time complexity for solving the N-Queens problem using backtracking is
derived as follows:
● For n=1, the solution is trivial, and there is no solution for n=2 and n=3.
● For n>1, the time complexity T(n) can be expressed as:
T(n)=nT(n−1)+c
T(n) = O(n!)
This is because the number of possibilities to place the queens decreases at each
step, but the total number of operations grows factorially as n increases.
Space complexity
Space complexity for this algorithm is O(n). The algorithm uses an auxiliary array
of length n to store just n positions.
22
Conclusion
23
Reference
1. Mukherjee, S., Datta, S., Chanda, P. B., & Pathak, P. (2015). Comparative
study of different algorithms to solve N queens problem. Int. J. Found.
Comput. Sci. Technol, 5(2), 15-27.
2. Russell, S. and Norvig, P. “Artificial Intelligence A Modern Approach”,
Second Edition, pp 139-140.
3. Letavec, C. and Ruggiero, J. 2002. “The n-queen problem”, Informs
Transaction on Education, volume 2 number 3, May 2002.
4. Thada, V., & Dhaka, S. (2014). Performance analysis of N-Queen problem
using backtracking and genetic algorithm techniques. International Journal of
Computer Applications, 102(7).
5. E. Horowitz ,S. Sahni,S.Rajasekaran, “ Fundamentals of Computer
Algorithms”,University Press India.2007.
6. Kondrak, G., & Van Beek, P. (1997). A theoretical evaluation of selected
backtracking algorithms. Artificial Intelligence, 89(1-2), 365-387.
7. Shivammiglani “Constraint Satisfaction Problems (CSP) in Artificial
Intelligence”, Oct 03, 2024.
8. Nguyễn Đức Kiên, Trường Đại học Công Nghệ , ĐHQGHN “ Đệ quy và thuật
toán quay lui” .
9. PT Nguyễn Tiến Thành (2024) “ Thuật toán quay lui Backtracking ”, August
19, 2024 in Students’ Seminar.
10. Haren Drakumar (2024) “Backtracking Algorithm” April 17, 2024.
11. GeeksforGeeks “ Introduction to Backtracking” June 24, 2024.
12. Pratham Sahani “Backtracking Meaning in DSA”, Feb 21, 2023.
24
Member’s contribution
Member Tasks
1. Took charge of creating a presentation
(PPT).
Dam Thanh Loan 25%
2. Provided guidelines on content development
22070714
3. Writing Chapter 2
Tran Thi Huong Ly 1. Took charge of finalizing the project report.
25%
21070569 2. Writing Chapter 1
Nguyen Thi Lan Anh 1. Writing Introduction
22070844 25%
2. Took charge of presenting the group's work
25