Skip to content

Commit 4d3661c

Browse files
Added M-coloring solution
1 parent 6eae49b commit 4d3661c

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

Programs/Backtracking/Mcolor.java

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
// Java program for m coloring problem
2+
3+
public class Mcolor {
4+
5+
// Number of vertices in the graph
6+
static int V = 4;
7+
8+
/* A utility function to print solution */
9+
static void printSolution(int[] color)
10+
{
11+
System.out.println(
12+
"Solution Exists:"
13+
+ " Following are the assigned colors ");
14+
for (int i = 0; i < V; i++)
15+
System.out.print(" " + color[i]);
16+
System.out.println();
17+
}
18+
19+
// check if the colored
20+
// graph is safe or not
21+
static boolean isSafe(boolean[][] graph, int[] color)
22+
{
23+
// check for every edge
24+
for (int i = 0; i < V; i++)
25+
for (int j = i + 1; j < V; j++)
26+
if (graph[i][j] && color[j] == color[i])
27+
return false;
28+
return true;
29+
}
30+
31+
/* This function solves the m Coloring
32+
problem using recursion. It returns
33+
false if the m colours cannot be assigned,
34+
otherwise, return true and prints
35+
assignments of colours to all vertices.
36+
Please note that there may be more than
37+
one solutions, this function prints one
38+
of the feasible solutions.*/
39+
static boolean graphColoring(boolean[][] graph, int m,
40+
int i, int[] color)
41+
{
42+
// if current index reached end
43+
if (i == V) {
44+
45+
// if coloring is safe
46+
if (isSafe(graph, color)) {
47+
48+
// Print the solution
49+
printSolution(color);
50+
return true;
51+
}
52+
return false;
53+
}
54+
55+
// Assign each color from 1 to m
56+
for (int j = 1; j <= m; j++) {
57+
color[i] = j;
58+
59+
// Recur of the rest vertices
60+
if (graphColoring(graph, m, i + 1, color))
61+
return true;
62+
color[i] = 0;
63+
}
64+
return false;
65+
}
66+
67+
// Driver code
68+
public static void main(String[] args)
69+
{
70+
71+
/* Create following graph and
72+
test whether it is 3 colorable
73+
(3)---(2)
74+
| / |
75+
| / |
76+
| / |
77+
(0)---(1)
78+
*/
79+
boolean[][] graph = {
80+
{ false, true, true, true },
81+
{ true, false, true, false },
82+
{ true, true, false, true },
83+
{ true, false, true, false },
84+
};
85+
int m = 3; // Number of colors
86+
87+
// Initialize all color values as 0.
88+
// This initialization is needed
89+
// correct functioning of isSafe()
90+
int[] color = new int[V];
91+
for (int i = 0; i < V; i++)
92+
color[i] = 0;
93+
94+
// Function call
95+
if (!graphColoring(graph, m, 0, color))
96+
System.out.println("Solution does not exist");
97+
}
98+
}
99+

0 commit comments

Comments
 (0)