-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathGraphColoring.java
More file actions
66 lines (52 loc) · 2.07 KB
/
Copy pathGraphColoring.java
File metadata and controls
66 lines (52 loc) · 2.07 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package util;
import java.util.*;
public class GraphColoring {
public Map<Integer, Integer> colorGraph(WeightedGraph graph) {
List<GraphEdge>[] vertices = graph.getVertices();
Map<Integer, Integer> colorMap = new HashMap<>();
// Iterate over each vertex
for (int vertex = 0; vertex < vertices.length; vertex++) {
// Find all neighboring colors
Set<Integer> neighborColors = new HashSet<>();
for (GraphEdge edge : vertices[vertex])
if (colorMap.containsKey(edge.getDestination()))
neighborColors.add(colorMap.get(edge.getDestination()));
// Find the color number that is not used by the neighbors
int color = 1;
while (neighborColors.contains(color))
color++;
colorMap.put(vertex, color);
}
return colorMap;
}
public static void main(String[] args) {
// Creating a graph that has 6 vertices
// 4
// 0-------- -----------3-------
// | \ / 3 \ 2
// | \ / 6 \
// | 4 2 ---------------------- 4
// | / \ /
// | / \ 1 / 3
// 1-------- ---------5---------
// 2
WeightedGraph graph = new WeightedGraph(6);
graph.addUndirectedEdge(0, 1, 4);
graph.addUndirectedEdge(0, 2, 4);
graph.addUndirectedEdge(1, 2, 2);
graph.addUndirectedEdge(2, 3, 3);
graph.addUndirectedEdge(2, 4, 6);
graph.addUndirectedEdge(2, 5, 1);
graph.addUndirectedEdge(3, 4, 2);
graph.addUndirectedEdge(5, 4, 3);
GraphColoring graphColoring = new GraphColoring();
Map<Integer, Integer> colorMap = graphColoring.colorGraph(graph);
System.out.println("Node colors:");
int maxColorValue = -1;
for (Map.Entry<Integer, Integer> entry : colorMap.entrySet()) {
maxColorValue = Math.max(maxColorValue, entry.getValue());
System.out.println("Node " + entry.getKey() + " -> Color " + entry.getValue());
}
System.out.println("Minimum number of colors used: " + maxColorValue);
}
}