Search⌘ K
AI Features

Solution: Color the Graph

Explore a greedy algorithm approach to color graph vertices by assigning the first available color while ensuring adjacent vertices differ. Understand the step-by-step process and its time complexity of O(V² + E) for optimal graph coloring solutions.

We'll cover the following...

Solution

Java
class Coloring {
public static void greedyColoring(Graph g) {
int numofVertices = g.getVertices();
int[] result = new int[numofVertices];
//Initialize vertices as unassigned
Arrays.fill(result, -1);
//Assign the first color to first vertex
result[0] = 0;
boolean[] available = new boolean[numofVertices];
// Assign colors to remaining V-1 vertices
Arrays.fill(available, true);
LinkedList < Integer > Llist[];
Llist = g.getAdj();
for (int i = 1; i < numofVertices; i++) {
Iterator < Integer > var = Llist[i].iterator();
while (var.hasNext()) {
int temp = var.next();
// Find the first available color
if (result[temp] != -1) {
available[result[temp]] = false;
}
}
int j;
for (j = 0; j < numofVertices; j++) {
if (available[j]) {
break;
}
}
result[i] = j; // Assign the found color
//reset the values
Arrays.fill(available, true);
}
for (int i = 0; i < numofVertices; i++) {
System.out.println("Vertex: " + i + " , " + "Color: " + result[i]);
}
}
}
class Main {
public static void main(String[] args) {
Graph g1 = new Graph(5);
g1.addEdge(0, 1);
g1.addEdge(0, 2);
g1.addEdge(1, 2);
g1.addEdge(1, 3);
g1.addEdge(2, 3);
g1.addEdge(3, 4);
Coloring.greedyColoring(g1);
System.out.println();
Graph g2 = new Graph(5);
g2.addEdge(0, 1);
g2.addEdge(0, 2);
g2.addEdge(1, 2);
g2.addEdge(1, 4);
g2.addEdge(2, 4);
g2.addEdge(4, 3);
Coloring.greedyColoring(g2);
}
}

Explanation

The solution is simple: assign the first available color and make that color unavailable for the adjacent vertices.

As seen above, start by coloring the first vertex with the first color. Then for the remaining vertices, color the current vertex with the lowest numbered color that has not been used on any previously colored vertices that are ...