Backtracking
Backtracking
Backtracking
• Example:
a
b c
d e
The 3-Coloring Problem
graphcolor(k)
1. for color=1 to 3
2. c[k]color;
3. if c is a legal coloring then set flag true and exit;
4. else if c is partial then graphcolor(k+1);
5. end for;
The 3-Coloring Problem
Iterative Algorithm
Input: An undirected graph G=(V, E).
Output: A 3-coloring c[1…n] of the vertices of G, where each c[j] is 1, 2, or 3.
1. for k1 to n
2. c[k]0;
3. end for;
4. flagfalse;
5. k1;
6. while k1
7. while c[k]2
8. c[k]c[k]+1;
9. if c is a legal coloring then set flagtrue and exit from the two while loops;
10. else if c is partial then kk+1;
11. end while;
12. c[k]0;
13. kk-1;
14. end while;
15. if flag then output c;
16. else output “no solution”;
• Given an undirected graph and a number m, determine if the graph can be
colored with at most m colors such that no two adjacent vertices of the graph are
colored with same color. Here coloring of a graph means assignment of colors to
all vertices.
• Input:
1) A 2D array graph[V][V] where V is the number of vertices in graph and graph[V]
[V] is adjacency matrix representation of the graph. A value graph[i][j] is 1 if there
is a direct edge from i to j, otherwise graph[i][j] is 0.
2) An integer m which is maximum number of colors that can be used.
• Output:
An array color[V] that should have numbers from 1 to m. color[i] should represent
the color assigned to the ith vertex. The code should also return false if the graph
cannot be colored with m colors.
• #include<stdio.h>
int G[50][50],x[50]; //G:adjacency matrix,x:colors
void next_color(int k){
int i,j;
x[k]=1; //coloring vertex with color1
for(i=0;i<k;i++)
•
• int main(){
int n,e,i,j,k,l;
printf("Enter no. of vertices : ");
scanf("%d",&n); //total vertices
printf("Enter no. of edges : ");
scanf("%d",&e); //total edges
for(i=0;i<n;i++)
for(j=0;j<n;j++)
G[i][j]=0; //assign 0 to all index of adjacency matrix
•
printf("Colors of vertices -->\n");
for(i=0;i<n;i++) //displaying color of each
vertex
printf("Vertex[%d] : %d\n",i+1,x[i]);
return 0;
}