Professional Documents
Culture Documents
ETCS-301
Semester: Vth
Group:5C2
RollNo:
1
INDEX
2
Recursion and Backtracking in path problems
and games
What is recursion?
3
The factorial function, often denoted as n!, describes the operation of
multiplying a number by all the positive integers smaller than it. For
example, 5! = 5*4*3*2*1. And 9! = 9*8*7*6*5*4*3*2*1.
Take a good close look at the above, and you may notice something
interesting. 5! can be written much more concisely as 5! = 5*4!.
int factorial(int n)
{
return n * factorial(n-1);
}
4
Backtracking Algorithm
Backtracking is an algorithmic-technique for solving problems
recursively by trying to build a solution incrementally, one piece at a
time, removing those solutions that fail to satisfy the constraints of the
problem at any point of time (by time, here, is referred to the time elapsed
till reaching any level of the search tree).
For example, consider the Sudoku solving Problem, we try filling digits
one by one. Whenever we find that current digit cannot lead to a solution,
we remove it (backtrack) and try next digit. This is better than naive
approach (generating all possible combinations of digits and then trying
every combination one by one) as it drops a set of permutations
whenever it backtracks.
5
How to determine if a problem can be solved using
Backtracking?
7
Snake and ladders || Recursion
N-Queens || Backtracking
8
Sudoku || Backtracking
Problem:
Given a partially filled 9×9 2D array ‘grid[9][9]’, the goal is to assign digits
(from 1 to 9) to the empty cells so that every row, column, and subgrid of
size 3×3 contains exactly one instance of the digits from 1 to 9.
Algorithm
Like all other Backtracking problems, we can solve Sudoku by one by
one assigning numbers to empty cells. Before assigning a number, we
check whether it is safe to assign. We basically check that the same
number is not present in the current row, current column and current 3X3
subgrid. After checking for safety, we assign the number, and recursively
check whether this assignment leads to a solution or not. If the
assignment doesn’t lead to a solution, then we try the next number for
9
the current empty cell. And if none of the number (1 to 9) leads to a
solution, we return false.
Now let’s try all this in practice with a simple 3x3 grid.
We now select the first spot (1,2) to work with. Since this is a 3x3 grid, we have
numbers 1 to 3 at our disposal and no sub-grids to worry about (sub-grids are
only a bother for grids with squared sides, like 4, 9, 16 etc.).
Let’s place number 1 in this spot and see if it fits.
10
Filling ‘1’ in spot (1, 2)
It does. Great. We can now select the next spot on the list (2,2) and do the same
thing again. This time however, it fails. We already have a 1 in this row. This
means that we must abandon candidate and repeat step 2 with the next
number — which is 2.
Huzzah! One more spot is filled. Also, it might not look like it, but we did just
perform backtracking on a single spot. We abandoned a candidate solution (1 at
spot (2,2)), visited a previous stage (empty spot (2,2)) and explored a new
candidate solution (number 2 at spot (2,2)).
When we move on to spot (2,3), we have another problem. As you can see, we
are all out of options. None of the possible numbers fit in. This means that we
must now abandon candidate and repeat step 2 with the next number. Only this
time, we must visit spot (2,2) first to fix spot (2,3).
11
Failure to fill spot (2, 3)
We need to fill number 3 in spot (2,2) and that will resolve the issue.
12
Unsolvable 3x3 puzzle (left) and Multi-solution 3x3 puzzle (right)
ALGORITHM COMPLEXITY :
O(n ^ m) where n is the number of possibilities for each square (i.e., 9 in classic
Sudoku) and m is the number of spaces that are blank.
14
Snake and Ladder game || RECURSION
Given a snake and ladder board, the user is required to reach the
destination or last cell from source or 1st cell. we are given the user
history of dice thrown and we find where does the user end (WIN means
he/she reaches the destination).
If the player reaches a cell which is base of a ladder, the player has to
climb up that ladder and if reaches a cell is mouth of the snake, has to go
down to the tail of snake without a dice throw.
code
snakesAnsladders(int src,int dest,int[] snakes,int[] moves,int mvidx)
if(src==0){
if(moves[mvidx]==1 || moves[mvidx]==6){
snakesAnsladders(1, dest, snakes, moves, mvidx+1);
}else{
snakesAnsladders(src, dest, snakes, moves, mvidx+1);
15
}
}else{
if(snakes[src]!=0){
snakesAnsladders(snakes[src], dest, snakes, moves, mvidx);
}else{
if(src + moves[mvidx] <= dest){
snakesAnsladders(src+moves[mvidx], dest, snakes, moves, mvidx
+1);
}else{
snakesAnsladders(src, dest, snakes, moves, mvidx+1);
}
}
}
}
A board of size 20 was taken and win is a situation where the user reaches 20
starting from 0 and can only start playing if he/she gets 1 or 6 first and in case the
user exhausts their moves and doesn’t reach the destination the final position
reached by the user is displayed
16
Rat in a maze || BACKTRACKING
A Maze is given as N*N binary matrix of blocks where source block is
the upper left most block i.e., maze[0][0] and destination block is lower
rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to
reach the destination. The rat can move in 8 directions: forward,
backward, up, diagonally upwards right, diagonally upwards left,
diagonally downwards right and diagonally downwards left,.
In the maze matrix, 0 means the block is a dead end and 1 means the
block can be used in the path from source to destination.
Naive Algorithm
Backtracking Algorithm
If destination is reached
Print the solution matrix
Else
a) Mark the current cell in solution as 1
b) Move forward in the horizontal direction and recursively
Check if this move leads to a solution.
c)If the move chosen in the above step doesn’t lead to a solution
then move in rest of the 7 directions and search for a solution.
17
d)If none of the above moves bring a solution the mark the cell
as 0
and return false
In the above figure when a 3*3 matrix is taken and certain path for
the movements of the rat are blocked, the solutions show how a rat
can move given he can move in 8 directions namely up, diagonally
north-east, right, diagonally south-east, down, diagonally south-
west, left and finally diagonally north-west
18
N Queen problem || BACKTRACKING
Problem Statement :
N queens problem is one of the most common examples of
backtracking. Our goal is to arrange N queens on an NxN chessboard
such that no queen can strike down any other queen. A queen can
attack horizontally, vertically, or diagonally.
What is Backtracking ?
Backtracking is finding the solution of a problem whereby the solution
depends on the previous steps taken. In backtracking, we first take a
step and then we see if this step taken is correct or not i.e., whether it
will give a correct answer or not. And if it doesn’t, then we just come
back and change our first step. In general, this is accomplished by
recursion. Thus, in backtracking, we first start with a partial sub-
solution of the problem (which may or may not lead us to the solution)
and then check if we can proceed further with this sub-solution or not.
If not, then we just come back and change it.
Thus, the general steps of backtracking are:
start with a sub-solution
check if this sub-solution will lead to the solution or not
If not, then come back and change the sub-solution and continue again
Initial Approach :
So, we start by placing the first queen anywhere arbitrarily and then
place the next queen in any of the safe places. We continue this process
until the number of unplaced queens becomes zero (a solution is found)
or no safe place is left. If no safe place is left, then we change the
position of the previously placed queen.
19
The above picture shows a 4x4 chessboard and we have to place 4
queens on it. So, we will start by placing the first queen in the first row.
Now, the second step is to place the second queen in a safe position.
Also, we can't place the queen in the first row, so we will try putting
the queen in the second row this time.
Let's place the third queen in a safe position, somewhere in the third
row.
Now, we can see that there is no safe place where we can put the last
queen. So, we will just change the position of the previous queen i.e.,
backtrack and change the previous decision.
20
Also, there is no other position where we can place the third queen, so
we will go back one more step and change the position of the second
queen.
And now we will place the third queen again in a safe position other
than the previously placed position in the third row.
We will continue this process and finally, we will get the solution as
shown below.
21
N_queen → This is the function where we are really implementing the
backtracking algorithm.
if(n==0) → If there is no queen left, it means all queens are placed and
we have got a solution.
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.
return true
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
23
The Knight’s tour || BACKTRACKING
Problem: The knight is placed on the first block of an empty board and,
moving according to the rules of chess, must visit each square exactly
once.
Following is chessboard with 8 x 8 cells. Numbers in cells indicate
move number of Knight.
Else
then remove this move from the solution vector and try other
alternative moves.
25