|
| 1 | +/*Write a program to implement the graph coloring problem with m=3 using back tracking method. Consider the |
| 2 | +following adjacency matrix for the graph. |
| 3 | + 1 2 3 4 |
| 4 | + 1 0 1 1 1 |
| 5 | + 2 1 0 1 0 |
| 6 | + 3 1 1 0 1 |
| 7 | + 4 1 0 1 0 |
| 8 | +*/ |
| 9 | +#include<stdio.h> |
| 10 | +#define v 4 |
| 11 | +void printsol(int color[]) { |
| 12 | + int i; |
| 13 | + printf("The assigned colors are: "); |
| 14 | + for (i = 0; i < v; i++) |
| 15 | + printf(" %d ", color[i]); |
| 16 | + printf("\n"); |
| 17 | +} |
| 18 | + |
| 19 | +int isSafe(int adj[v][v], int color[]) { |
| 20 | + int i,j; |
| 21 | + for (i = 0; i < v; i++) |
| 22 | + for (j = i + 1; j < v; j++) |
| 23 | + if (adj[i][j] && color[j] == color[i]){ |
| 24 | + return 1; |
| 25 | + } |
| 26 | + return 0; |
| 27 | +} |
| 28 | +int graphcolor(int adj[v][v], int m, int i, int color[v]){ |
| 29 | + int j; |
| 30 | + if (i == v){ // If we got all the vertex colored we check if it is safe |
| 31 | + if (isSafe(adj, color) == 0) { |
| 32 | + // If yes we print solution and return 0 |
| 33 | + printsol(color); |
| 34 | + return 0; |
| 35 | + } else{ |
| 36 | + return 1; |
| 37 | + } |
| 38 | + } |
| 39 | + //Recursively colors all the vertex |
| 40 | + for(j=1;j<=m;j++){ |
| 41 | + color[i] = j; |
| 42 | + if (graphcolor(adj,m,i+1,color) == 0){ // Since we returned 0 i.e we got one solution we return the func |
| 43 | + return 0; |
| 44 | + } |
| 45 | + color[i] = 0; // If we didn't get safe solu (i.e return value is 1) we start again |
| 46 | + } |
| 47 | + return 1; |
| 48 | +} |
| 49 | + |
| 50 | +int main(){ |
| 51 | + int i,j,m; |
| 52 | + printf("Enter the number of colors [m] : "); |
| 53 | + scanf("%d",&m); |
| 54 | + int adj[v][v]; |
| 55 | + printf("\nEnter values of the Adjacency Matrix: \n"); |
| 56 | + for(i=0;i<v;i++){ |
| 57 | + for(j=0;j<v;j++){ |
| 58 | + printf("\nEnter the value of adj[%d][%d]: ",i,j); |
| 59 | + scanf("%d",&adj[i][j]); |
| 60 | + } |
| 61 | + printf("\n"); |
| 62 | + } |
| 63 | + printf("\n\n"); |
| 64 | + printf("Adjacency Matrix: \n"); |
| 65 | + for(i=0;i<v;i++){ |
| 66 | + for(j=0;j<v;j++){ |
| 67 | + printf("%d ",adj[i][j]); |
| 68 | + } |
| 69 | + printf("\n"); |
| 70 | + } |
| 71 | + printf("\nThe value of m is: %d \nThe value of v is: %d\n",m,v); |
| 72 | + |
| 73 | + int color[v]; //Keeps record of the color, each vertex is colored with |
| 74 | + for (i = 0; i < v; i++){ |
| 75 | + color[i] = 0; //first set all the nodes color as 0 |
| 76 | + } |
| 77 | + |
| 78 | + if (graphcolor(adj, m, 0, color) == 1){ |
| 79 | + printf("Solution does not exist"); |
| 80 | + } |
| 81 | + return 0; |
| 82 | +} |
| 83 | + |
0 commit comments