CS19341
Design and Analysis of Algorithms
BACKTRACKING
Graph Coloring
Problem Statement
Let ‘G’ be a graph and ‘m’ be an integer.
The m-colorabiltiy decision problem is
finding whether the nodes of ‘G’ can be
colored using ‘m’ colors in such a way
that no two adjacent nodes have the same
color.
Problem Statement
The m-colorabiltiy optimization problem
is finding the smallest integer ‘m’ for
which the Graph‘G’ can be colored.
The integer ‘m’ is referred as the
chromatic number.
APPLICATIONS –Scheduling
APPLICATIONS –Solving Suduko
Backtracking Solution
The following steps are to be followed to
perform valid coloring for the graph G=(V,E).
1. Order the nodes arbitrarily
2. Assign the first node with a color.
3. Given the partial assignments of colors
(c1,c2,c3……ci-1) to first i-1 nodes, try to find the
color for the ith node.
4. If there are no possible color for ith node then
backtrack and change the option for previous
node.
Example 1
Consider a Graph=(V,E) where V={v1,v2,v3,v4} and E={(1,2),(1,3),(2,3),(2,4),(3,4) and m=3,find
the valid coloring for graph G.
2 3
4
Example 1
Consider a Graph=(V,E) where V={v1,v2,v3,v4} and E={(1,2),(1,3),(2,3),(2,4),(3,4) and m=3,find
the valid coloring for graph G.
SOLUTION
1. Order the nodes :1,2,3,4 NODE
1
2. M=[Link] it be Red(R),Blue(B) and Green(G)
Example 1
Consider a Graph=(V,E) where V={v1,v2,v3,v4} and E={(1,2),(1,3),(2,3),(2,4),(3,4) and m=3,find
the valid coloring for graph G.
SOLUTION
1. Order the nodes :1,2,3,4 NODE
1
2. M=[Link] it be Red(R),Blue(B) and Green(G)
NODE
2
Example 1
Consider a Graph=(V,E) where V={v1,v2,v3,v4} and E={(1,2),(1,3),(2,3),(2,4),(3,4) and m=3,find
the valid coloring for graph G.
SOLUTION
1. Order the nodes :1,2,3,4 NODE
1
2. M=[Link] it be Red(R),Blue(B) and Green(G)
NODE
2
NODE
3
Example 1
NODE SOLUTION :
1 NODE 1:RED
NODE 2:BLUE 1
NODE 3:GREEN
NODE
NODE 4:RED
2
NODE
2 3
3
NODE 4
4
Example 2
Consider the following states of India v={Tamilnadu, Kerala, Karnataka,
Goa,Telengana},color the states in such a way that no two adjacent states have the same color.
Check is it possible to color with 2 colors or 3 colors.
Representing the problem as a
graph coloring problem
Example 2
Example 2
Example 3
You have n gardens, labeled from 1 to n, and an array paths where paths[i] =
[xi, yi] describes a bidirectional path between garden xi to garden yi. In each
garden, you want to plant one of 4 types of flowers. All gardens have at most
3 paths coming into or leaving [Link] task is to choose a flower type for each
garden such that, for any two gardens connected by a path, they have
different types of flowers.
Types of flowers=1,2,3,4
Input: n = 3, paths = [[1,2],[2,3],[3,1]]
Input: n = 4, paths = [[1,2],[3,4]]
Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
Algorithm
Algorithm