-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph-coloring.java
43 lines (34 loc) · 1.21 KB
/
graph-coloring.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Problem link - https://www.geeksforgeeks.org/graph-coloring-applications/
class solve {
// Function to determine if graph can be coloured with at most M colours
// such
// that no two adjacent vertices of graph are coloured with same colour.
public boolean graphColoring(boolean graph[][], int m, int n) {
int colors[] = new int[n]; // 0 means no color is assigned
if(solve(graph, m, colors, 0, n)){
return true;
}
return false;
}
private boolean solve(boolean graph[][], int m, int colors[], int v, int n){
if(v == n) return true;
for(int c = 1; c <= m; c++){
if(isSafe(graph, v, colors, c, n)){
colors[v] = c;
if(solve(graph, m, colors, v + 1, n)){
return true;
}
colors[v] = 0;
}
}
return false;
}
private boolean isSafe(boolean graph[][], int v, int[] colors, int c, int n){
for(int i = 0; i < n; i++){
if(graph[v][i] && c == colors[i]){
return false;
}
}
return true;
}
}