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

Backtracking

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Backtracking

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Backtracking

Backtracking is a general algorithmic technique used to solve problems incrementally by trying


out partial solutions and discarding them if they are not suitable, effectively "backtracking" to try
other options. It is commonly applied to constraint satisfaction problems, combinatorial
problems, and puzzles where a sequence of choices must be made, and not all choices lead to a
solution.

How Backtracking Works:

1. Recursion and Decision Trees: The problem is approached by making a series of


decisions recursively. Each decision narrows down the problem, exploring one branch of
the decision tree at a time.

2. Base Case: If a solution is found (the base case of the recursion), the algorithm returns
the solution.

3. Failure and Backtracking: If a partial solution turns out to be invalid or doesn't lead to a
solution, the algorithm "backtracks" by undoing the last decision and tries a different
path (another branch of the decision tree).

4. Pruning (Optional): If a decision path can be identified early as invalid (because it


cannot lead to a solution), the algorithm can "prune" that branch, making it more
efficient by not exploring all possibilities.

Common Problems Solved with Backtracking:

• N-Queens Problem: Placing N queens on an N×N chessboard so that no two queens


threaten each other.

• Sudoku Solver: Filling a 9×9 grid with digits while respecting Sudoku's constraints.

• Knight's Tour: Moving a knight on a chessboard to visit every square exactly once.

• Subset Sum Problem: Finding subsets of a set that add up to a particular value.

• String Permutations and Combinations: Generating all possible combinations or


permutations of a set.
N-Queens Problem

The goal is to place N queens on an N×N chessboard such that no two queens threaten each
other (i.e., no two queens share the same row, column, or diagonal).

1. Start by placing a queen in the first row.

2. Try to place a queen in the next row where it doesn't threaten the previous one.

3. If a conflict arises, backtrack to the previous row and move the queen to a different
column.

4. Repeat until all queens are placed successfully or all options are exhausted.

Algorithm for Solving the N-Queens Problem Using Backtracking

Steps:

1. Place queens row by row: Start placing queens from the first row and proceed to place
one queen in each subsequent row.

2. Check for safe placement: For each row, try placing a queen in different columns,
ensuring that the queen does not attack any previously placed queens. A queen is safe if
there is no other queen in the same column or diagonal.

3. Recursion: Once a queen is placed in a valid position, move to the next row and repeat
the process for placing the next queen.

4. Backtracking: If placing a queen in any column of a particular row leads to an invalid


configuration (i.e., no safe position for a queen in the next row), backtrack to the
previous row, remove the last placed queen, and try the next available column in that
row.

5. Base case: When queens are placed successfully in all rows (i.e., when the row index
equals N), a solution is found.

6. Continue exploring: Backtrack further to explore all possible placements to find all valid
solutions.

Example of 4-Queens Problem:

Consider the 4-Queens problem, where N = 4. The algorithm will try to place 4 queens on a 4×4
board.

• Start by placing the first queen in the first row (in any of the 4 columns).

• Then, place the second queen in the second row in a valid column that doesn’t conflict
with the first queen.

• Proceed to the third row and repeat the process.

• If you encounter a conflict in any row, backtrack to the previous row, remove the queen,
and try a different column.
Subset-Sum Problem is finding a subset of a given set S = {s1,s2….sn} of n positive integers
whose sum is equal to a given positive integer d.

For example, for S = {1, 2, 5, 6, 8) and d = 9, there are two solutions: {1, 2, 6} and {1, 8}. Of
course, some instances of this problem may have no solutions.

It is convenient to sort the set‘s elements in increasing order. So we will assume

that s1 ≤ s2 ≤ ……. ≤ sn

The state-space tree can be constructed as a binary tree as that in the following figure for the
instances S = (3, 5, 6, 7) and d = 15.

The root of the tree represents the starting point, with no decisions about the given elements
made as yet.

Its left and right children represent, respectively, inclusion and exclusion ofs1 in a set being
sought.

Similarly, going to the left from a node of the first level corresponds to inclusion of s2, while
going to the right corresponds to its exclusion, and soon.

Thus, a path from the root to a node on the ith level of the tree indicates which of the first i
numbers have been included in the subsets represented by that node.
We record the value of s‘ the sum of these numbers, in the node, Ifs is equal to d. we have a
solution to the problem.

We can either, report this result and stop or, if all the solutions need to he found, continue by
backtracking to the node‘s parent.

If s‘ is not equal to d, we can terminate the node as nonpromising if either of the two inequalities
holds:

Backtracking Algorithm for Subset Sum Problem

The algorithm works by exploring all possible subsets of the given set. It starts by considering
each element, deciding whether to include it in the subset or not, and recurses to check the
sum of the resulting subset. If a valid subset is found, the algorithm terminates.

Steps:

1. Base Cases:

o If the sum of the subset equals the target sum T, a solution is found.

o If the sum of the subset exceeds T, or if there are no more elements to consider,
the algorithm backtracks.

2. Recursive Exploration:

o For each element in the set, the algorithm has two choices:

▪ Include the element in the current subset.

▪ Exclude the element and move to the next element.

3. Backtracking:

o If including or excluding an element doesn't lead to a valid solution, the


algorithm backtracks by undoing the last decision and trying the next possible
configuration.
Graph coloring

The Graph Coloring Problem is a well-known combinatorial problem where the goal is to assign
colors to the vertices of a graph such that no two adjacent vertices share the same colour, while
using as few colors as possible. This is often referred to as the k-colouring problem, where k is
the maximum number of colors that can be used.

Graph coloring can be solved using various algorithms, including backtracking. Here is a
description of the backtracking algorithm for the graph colouring problem.

Problem Statement:

Given a graph G=(V,E) with V vertices and E edges, and a number k, determine if the vertices of
the graph can be colored with at most k colors so that no two adjacent vertices share the same
color.

Steps in the Backtracking Algorithm:

1. Choose a vertex: Start by selecting a vertex and try to assign it a color from the available
k colors.

2. Check constraints: For each vertex, assign a color such that no adjacent vertex has the
same color (this is called the valid coloring constraint).

3. Recursion: Move to the next vertex and repeat the process. If all vertices are colored
without any conflicts, the solution is found.

4. Backtrack: If no valid color can be assigned to a vertex, backtrack to the previous vertex
and try a different color for it.

5. Base case: If all vertices are successfully colored, return the solution; otherwise, if no
solution exists, return failure.
Let G be a graph and m be a positive integer.

The problem is to color the vertices of G using only m colors in such a way that no two adjacent
nodes / vertices have the same color.

It is necessary to find the smallest integer m and m is referred to as the chromatic number of G.

A special case of graph coloring problem is the four color problem for planar graphs.

A graph is planar iff it can be drawn in a plane in such a way that no two edges cross each other.
4- colour problem for planar graphs.

Given any map, can the regions be colored in such a way that no two adjacent regions have the
same colour with only four colors?

A map can be transformed into a graph by representing each region of map into a node and if
two regions are adjacent, then the corresponding nodes are joined by an edge.

For many years it was known that 5 colors are required to color any map.

After a several hundred years, mathematicians with the help of a computer showed that 4
colors are sufficient.

Example: • Program and run m coloring algorithm using as data the complete graphs of size
n=2, 3, 4, 5, 6 and 7. Let the desired number of colors be k=n and k=n/2

You might also like