Solution: Color the Graph
This review provides a detailed analysis of the solution to the graph coloring problem.
We'll cover the following...
Solution
Press + to interact
main.java
Graph.java
class Coloring {public static void greedyColoring(Graph g) {int numofVertices = g.getVertices();int[] result = new int[numofVertices];//Initialize vertices as unassignedArrays.fill(result, -1);//Assign the first color to first vertexresult[0] = 0;boolean[] available = new boolean[numofVertices];// Assign colors to remaining V-1 verticesArrays.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 colorif (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 valuesArrays.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 ...