D7 Recursive Problem Solving and Intro to Backtracking
D7 Recursive Problem Solving and Intro to Backtracking
Solving &
Backtracking
Ashwin Perti
What is Recursion?
2. Handle simplest case - the base case(s) No recursive call needed (that’s why it is
the base case!)
3. Write the recursive call Input to call must be slightly simpler/smaller to move
towards the base case
Recursive Problem-Solving
{
// If length of string is 1 or 0
if (str[0] == '\0' || str[1] == '\0')
Exercises
return str;
/* Check if the first character of the rem_string matches with the first
character of the original string */
Explain how the Fibonacci sequence can be generated using recursion. // Remove first character
return (rem_str + 1);
}
/* If remaining string becomes empty and last removed character is same as
first character of original string. This is needed for a string like
"acbbcddc“ */
if (rem_str[0] == '\0' && *last_removed == str[0])
return rem_str;
3 Exercise 3: Recursively remove all adjacent duplicates
/* If the two first characters of str and rem_str don't match, append first
character of str before the first character of rem_str. */
Demonstrate how to remove adjacent redundancy from a string rem_str--;
rem_str[0] = str[0];
recursively. return rem_str;
}
// Function to remove
char* removes(char* str){
char last_removed = '\0';
return removeUtil(str, &last_removed);
Example: How number of nodes in a binary tree can be calculated using recursion?
return 1;
else
return getLeafCount(node->left) +
getLeafCount(node->right);
}
Example: How a binary tree can be converted into its mirror form using recursion?
Clearly define the conditions that stop the Break down the problem into smaller parts
recursion, ensuring efficient coding. and comprehend their relationships for
effective problem-solving.
return result;
}
Tail Recursion
A recursive function is tail recursive when recursive call is the last thing executed by the function.
void printFun(test)
{
if (test<1)
return;
else
{
printf("%d", test);
// no statement to execute after recursive call
printFun(test-1);
return;
}
}
long factorial(int n)
{
if (n == 0)
return 1; Is it also TR?
else
return(n * factorial(n-1));
}
•Mean of Array using Recursion
•Sum of natural numbers using recursion
•Decimal to binary number using recursion
•Sum of array elements using recursion
•Print reverse of a string using recursion
•Program for length of a string using recursion
•Sum of digit of a number using recursion
•Tail recursion to calculate sum of array elements.
•Program to print first n Fibonacci Numbers
•Program for factorial of a number
•Recursive Programs to find Minimum and Maximum elements of
array
•Recursively remove all adjacent duplicates
•Sort the Queue using Recursion
•Reversing a queue using recursion
•Delete a linked list using recursion
•Length of longest palindromic sub-string : Recursion
•Program for Tower of Hanoi Algorithm
•Find geometric sum of the series using recursion
•Convert a String to an Integer using Recursion
•DFS traversal of a Tree
•How to Sort a Stack using Recursion
•Reverse a Doubly linked list using recursion
•Check if a string is a scrambled form of another string
•N Queen Problem
•Algorithm to Solve Sudoku
Backtracking: Idea
• Backtracking is a technique used to solve problems with a large search
space, by systematically trying and eliminating possibilities.
• A standard example of backtracking would be going through a maze.
– At some point, you might have two options of which direction to go:
Portion A
Junction
Portion B
One strategy would be to try going through Portion A of
the maze. o n
n cti
J u
If you get stuck before you find your way out, then
you "backtrack" to the junction.
Portion B
Portion A
so you then start searching in Portion B
Backtracking
dead end
?
dead end
dead end
?
start ? ?
dead end
dead end
success!
Backtracking
• Instead, the stack of recursive calls does most of the bookkeeping (i.e., keeps track of which
locations we’ve tried so far.)
• Backtracking can easily be used to iterate through all subsets or permutations of a set.
Define a function that explores paths and Discuss how the algorithm tries moving in
backtracks when necessary. all possible directions to find the right path.
Emphasize the importance of marking the Show step-by-step visuals of the algorithm
path and undoing marks during in action to aid understanding.
backtracking for methodical navigation.
Rat in a Maze - Code Snippet
Consider a rat placed at (0, 0) in a square matrix of order N * N. It has to reach
the destination at (N – 1, N – 1). Find all possible paths that the rat can take to
reach from source to destination. The directions in which the rat can move
are ‘U'(up), ‘D'(down), ‘L’ (left), ‘R’ (right). Value 0 at a cell in the matrix
represents that it is blocked and rat cannot move to it while value 1 at a cell in
the matrix represents that rat can be travel through it.
Step-by-step approach:
• Create isValid() function to check if a cell at position (r, c) is
inside the maze and unblocked.
• Create findPath() to get all valid paths:
• Base case: If the current position is the bottom-right cell,
add the current path to the result and return.
• Mark the current cell as blocked.
• Iterate through all possible directions.
• Calculate the next position based on the current
direction.
• If the next position is valid (i.e, if isValid() return true),
append the direction to the current path and recursively
call the findPath() function for the next cell.
• Backtrack by removing the last direction from the
current path.
Applications of Maze Solving Approach
1.Robotics:
Autonomous robots often use maze-solving algorithms to navigate through unknown
environments. This is crucial for tasks like exploration, search and rescue missions, and automated
warehouse systems.
2.Computer Games/ Puzzle Solving :
Maze-solving algorithms are frequently used in the development of computer games, particularly in
designing levels and creating challenging environments for players.
3.Path Planning/ Network Routing :
Beyond mazes, these algorithms are applied to more complex path-planning problems in fields
such as logistics, transportation, and traffic management and to find the most efficient path for
data transmission in a network.
4.Artificial Intelligence and Machine Learning:
Maze-solving problems are often used as benchmarks or exercises in AI and machine learning
courses. Reinforcement learning algorithms, for example, can be trained to solve mazes as part
of their learning process.
5.Maze Generation:
Algorithms used for maze solving can also be applied to generate interesting and challenging
mazes for entertainment purposes, such as in video games or puzzles.
6.Telecommunications:
Maze-solving principles are applicable in optimizing the routing of signals in telecommunications
networks, helping to ensure efficient data transmission.
N Queens Problem
1.Base Case: In the N-Queens problem, the base case occurs when all queens are
successfully placed on the board without conflicting with each other.
2.Constraint Satisfaction: The constraint is that no two queens can share the
same row, column, or diagonal. Ensuring that each queen is placed in a position that
satisfies these constraints is crucial.
3.Decision Space: At each step, we need to decide the row where the next queen
will be placed. The decision space consists of the remaining rows that are not
threatened by the already placed queens.
4.Solution Space: The solution space for the N-Queens problem is the set of all
possible arrangements of queens on the chessboard. The size of the solution space
is N! since there are N choices for the queen's position in the first row, N−1 choices for
the second row, and so on.
8.Corner Cases: Corner cases in the N-Queens problem may include scenarios where
N=0 or N=1, where there are no valid solutions since there are no queens to place
or only one queen on the board, respectively.
10.Early Termination: If we detect that it's impossible to place N queens on the board
due to conflicts, we can terminate the backtracking process early, saving
computational resources.
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.
4) If all rows have been tried and nothing worked,
return false to trigger backtracking.
https://dipeshpatil.github.io/algorithms-visualiser/#/
https://visualgo.net/en
https://algorithm-visualizer.org/
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html