Graph Coloring Using Greedy Algorithm
Last Updated : 10 Oct, 2023
We introduced graph coloring and applications in previous post. As discussed in the previous post, graph coloring is widely used. Unfortunately, there is no efficient algorithm available for coloring a graph with minimum number of colors as the problem is a known NP Complete problem. There are approximate algorithms to solve the problem though. Following is the basic Greedy Algorithm to assign colors. It doesn't guarantee to use minimum colors, but it guarantees an upper bound on the number of colors. The basic algorithm never uses more than d+1 colors where d is the maximum degree of a vertex in the given graph.
Graph Coloring Using Greedy Algorithm:
- Color first vertex with first color.
- Do following for remaining V-1 vertices.
- Consider the currently picked vertex and color it with the lowest numbered color that has not been used on any previously colored vertices adjacent to it. If all previously used colors appear on vertices adjacent to v, assign a new color to it.
Below is the implementation of the above Greedy Algorithm.
C++ // A C++ program to implement greedy algorithm for graph coloring #include <iostream> #include <list> using namespace std; // A class that represents an undirected graph class Graph { int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists public: // Constructor and destructor Graph(int V) { this->V = V; adj = new list<int>[V]; } ~Graph() { delete [] adj; } // function to add an edge to graph void addEdge(int v, int w); // Prints greedy coloring of the vertices void greedyColoring(); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected } // Assigns colors (starting from 0) to all vertices and prints // the assignment of colors void Graph::greedyColoring() { int result[V]; // Assign the first color to first vertex result[0] = 0; // Initialize remaining V-1 vertices as unassigned for (int u = 1; u < V; u++) result[u] = -1; // no color is assigned to u // A temporary array to store the available colors. True // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices bool available[V]; for (int cr = 0; cr < V; cr++) available[cr] = false; // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = true; // Find the first available color int cr; for (cr = 0; cr < V; cr++) if (available[cr] == false) break; result[u] = cr; // Assign the found color // Reset the values back to false for the next iteration for (i = adj[u].begin(); i != adj[u].end(); ++i) if (result[*i] != -1) available[result[*i]] = false; } // print the result for (int u = 0; u < V; u++) cout << "Vertex " << u << " ---> Color " << result[u] << endl; } // Driver program to test above function int main() { Graph g1(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); cout << "Coloring of graph 1 \n"; g1.greedyColoring(); Graph g2(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); cout << "\nColoring of graph 2 \n"; g2.greedyColoring(); return 0; }
Java // A Java program to implement greedy algorithm for graph coloring import java.io.*; import java.util.*; import java.util.LinkedList; // This class represents an undirected graph using adjacency list class Graph { private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List //Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); //Graph is undirected } // Assigns colors (starting from 0) to all vertices and // prints the assignment of colors void greedyColoring() { int result[] = new int[V]; // Initialize all vertices as unassigned Arrays.fill(result, -1); // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available colors. False // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices boolean available[] = new boolean[V]; // Initially, all colors are available Arrays.fill(available, true); // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable Iterator<Integer> it = adj[u].iterator() ; while (it.hasNext()) { int i = it.next(); if (result[i] != -1) available[result[i]] = false; } // Find the first available color int cr; for (cr = 0; cr < V; cr++){ if (available[cr]) break; } result[u] = cr; // Assign the found color // Reset the values back to true for the next iteration Arrays.fill(available, true); } // print the result for (int u = 0; u < V; u++) System.out.println("Vertex " + u + " ---> Color " + result[u]); } // Driver method 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); System.out.println("Coloring of graph 1"); g1.greedyColoring(); 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); System.out.println("Coloring of graph 2 "); g2.greedyColoring(); } } // This code is contributed by Aakash Hasija
Python3 # Python3 program to implement greedy # algorithm for graph coloring def addEdge(adj, v, w): adj[v].append(w) # Note: the graph is undirected adj[w].append(v) return adj # Assigns colors (starting from 0) to all # vertices and prints the assignment of colors def greedyColoring(adj, V): result = [-1] * V # Assign the first color to first vertex result[0] = 0; # A temporary array to store the available colors. # True value of available[cr] would mean that the # color cr is assigned to one of its adjacent vertices available = [False] * V # Assign colors to remaining V-1 vertices for u in range(1, V): # Process all adjacent vertices and # flag their colors as unavailable for i in adj[u]: if (result[i] != -1): available[result[i]] = True # Find the first available color cr = 0 while cr < V: if (available[cr] == False): break cr += 1 # Assign the found color result[u] = cr # Reset the values back to false # for the next iteration for i in adj[u]: if (result[i] != -1): available[result[i]] = False # Print the result for u in range(V): print("Vertex", u, " ---> Color", result[u]) # Driver Code if __name__ == '__main__': g1 = [[] for i in range(5)] g1 = addEdge(g1, 0, 1) g1 = addEdge(g1, 0, 2) g1 = addEdge(g1, 1, 2) g1 = addEdge(g1, 1, 3) g1 = addEdge(g1, 2, 3) g1 = addEdge(g1, 3, 4) print("Coloring of graph 1 ") greedyColoring(g1, 5) g2 = [[] for i in range(5)] g2 = addEdge(g2, 0, 1) g2 = addEdge(g2, 0, 2) g2 = addEdge(g2, 1, 2) g2 = addEdge(g2, 1, 4) g2 = addEdge(g2, 2, 4) g2 = addEdge(g2, 4, 3) print("\nColoring of graph 2") greedyColoring(g2, 5) # This code is contributed by mohit kumar 29
C# // A C# program to implement greedy algorithm for graph coloring using System; using System.Collections.Generic; // This class represents an undirected graph using adjacency list class Graph { private int V; // No. of vertices private List<int>[] adj; //Adjacency List //Constructor public Graph(int v) { V = v; adj = new List<int>[v]; for (int i=0; i<v; ++i) adj[i] = new List<int>(); } //Function to add an edge into the graph public void addEdge(int v,int w) { adj[v].Add(w); adj[w].Add(v); //Graph is undirected } // Assigns colors (starting from 0) to all vertices and // prints the assignment of colors public void greedyColoring() { int[] result = new int[V]; // Initialize all vertices as unassigned for(int i = 0; i < V; i++) { result[i] = -1; } // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available colors. False // value of available[cr] would mean that the color cr is // assigned to one of its adjacent vertices bool[] available = new bool[V]; // Initially, all colors are available for(int i = 0; i < V; i++) { available[i] = true; } // Assign colors to remaining V-1 vertices for (int u = 1; u < V; u++) { // Process all adjacent vertices and flag their colors // as unavailable foreach (int i in adj[u]) { if (result[i] != -1) available[result[i]] = false; } // Find the first available color int cr; for (cr = 0; cr < V; cr++) { if (available[cr]) break; } result[u] = cr; // Assign the found color // Reset the values back to true for the next iteration for(int i = 0; i < V; i++) { available[i] = true; } } // print the result for (int u = 0; u < V; u++) Console.WriteLine("Vertex " + u + " ---> Color " + result[u]); } // Driver method 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); Console.WriteLine("Coloring of graph 1"); g1.greedyColoring(); 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); Console.WriteLine("\nColoring of graph 2"); g2.greedyColoring(); } }
JavaScript <script> // Javascript program to implement greedy // algorithm for graph coloring // This class represents a directed graph // using adjacency list representation class Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); for(let i = 0; i < v; ++i) this.adj[i] = []; this.Time = 0; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); // Graph is undirected this.adj[w].push(v); } // Assigns colors (starting from 0) to all // vertices and prints the assignment of colors greedyColoring() { let result = new Array(this.V); // Initialize all vertices as unassigned for(let i = 0; i < this.V; i++) result[i] = -1; // Assign the first color to first vertex result[0] = 0; // A temporary array to store the available // colors. False value of available[cr] would // mean that the color cr is assigned to one // of its adjacent vertices let available = new Array(this.V); // Initially, all colors are available for(let i = 0; i < this.V; i++) available[i] = true; // Assign colors to remaining V-1 vertices for(let u = 1; u < this.V; u++) { // Process all adjacent vertices and // flag their colors as unavailable for(let it of this.adj[u]) { let i = it; if (result[i] != -1) available[result[i]] = false; } // Find the first available color let cr; for(cr = 0; cr < this.V; cr++) { if (available[cr]) break; } // Assign the found color result[u] = cr; // Reset the values back to true // for the next iteration for(let i = 0; i < this.V; i++) available[i] = true; } // print the result for(let u = 0; u < this.V; u++) document.write("Vertex " + u + " ---> Color " + result[u] + "<br>"); } } // Driver code let 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); document.write("Coloring of graph 1<br>"); g1.greedyColoring(); document.write("<br>"); let 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); document.write("Coloring of graph 2<br> "); g2.greedyColoring(); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Coloring of graph 1 Vertex 0 ---> Color 0 Vertex 1 ---> Color 1 Vertex 2 ---> Color 2 Vertex 3 ---> Color 0 Vertex 4 ---> Color 1 Coloring of graph 2 Vertex 0 ---> Color 0 Vertex 1 ---> Color 1 Vertex 2 ---> Color 2 Vertex 3 ---> Color 0 Vertex 4 ---> Color 3
Time Complexity: O(V^2 + E), in worst case.
Auxiliary Space: O(1), as we are not using any extra space.
Analysis of Graph Coloring Using Greedy Algorithm:
The above algorithm doesn't always use minimum number of colors. Also, the number of colors used sometime depend on the order in which vertices are processed. For example, consider the following two graphs. Note that in graph on right side, vertices 3 and 4 are swapped. If we consider the vertices 0, 1, 2, 3, 4 in left graph, we can color the graph using 3 colors. But if we consider the vertices 0, 1, 2, 3, 4 in right graph, we need 4 colors.

So the order in which the vertices are picked is important. Many people have suggested different ways to find an ordering that work better than the basic algorithm on average. The most common is Welsh–Powell Algorithm which considers vertices in descending order of degrees.
How does the basic algorithm guarantee an upper bound of d+1?
Here d is the maximum degree in the given graph. Since d is maximum degree, a vertex cannot be attached to more than d vertices. When we color a vertex, at most d colors could have already been used by its adjacent. To color this vertex, we need to pick the smallest numbered color that is not used by the adjacent vertices. If colors are numbered like 1, 2, ...., then the value of such smallest number must be between 1 to d+1 (Note that d numbers are already picked by adjacent vertices).
This can also be proved using induction. See this video lecture for proof.
Similar Reads
Greedy Algorithms Greedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Greedy Algorithm Tutorial Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following pro
9 min read
Greedy Algorithms General Structure A greedy algorithm solves problems by making the best choice at each step. Instead of looking at all possible solutions, it focuses on the option that seems best right now.Example of Greedy Algorithm - Fractional KnapsackProblem structure:Most of the problems where greedy algorithms work follow thes
5 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of m
3 min read
Greedy Approach vs Dynamic programming Greedy approach and Dynamic programming are two different algorithmic approaches that can be used to solve optimization problems. Here are the main differences between these two approaches: Greedy Approach:The greedy approach makes the best choice at each step with the hope of finding a global optim
2 min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms:Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.
4 min read
Standard Greedy algorithms
Activity Selection Problem | Greedy Algo-1Given n activities with start times in start[] and finish times in finish[], find the maximum number of activities a single person can perform without overlap. A person can only do one activity at a time. Examples: Input: start[] = [1, 3, 0, 5, 8, 5], finish[] = [2, 4, 6, 7, 9, 9]Output: 4Explanatio
13 min read
Job Sequencing ProblemGiven two arrays: deadline[] and profit[], where the index of deadline[] represents a job ID, and deadline[i] denotes the deadline for that job and profit[i] represents profit of doing ith job. Each job takes exactly one unit of time to complete, and only one job can be scheduled at a time. A job ea
13 min read
Huffman Coding | Greedy Algo-3Huffman coding is a lossless data compression algorithm. The idea is to assign variable-length codes to input characters, lengths of the assigned codes are based on the frequencies of corresponding characters. The variable-length codes assigned to input characters are Prefix Codes, means the codes (
12 min read
Huffman DecodingWe have discussed Huffman Encoding in a previous post. In this post, decoding is discussed. Examples: Input Data: AAAAAABCCCCCCDDEEEEEFrequencies: A: 6, B: 1, C: 6, D: 2, E: 5 Encoded Data: 0000000000001100101010101011111111010101010 Huffman Tree: '#' is the special character usedfor internal nodes
15 min read
Water Connection ProblemYou are given n houses in a colony, numbered from 1 to n, and p pipes connecting these houses. Each house has at most one outgoing pipe and at most one incoming pipe. Your goal is to install tanks and taps efficiently.A tank is installed at a house that has one outgoing pipe but no incoming pipe.A t
8 min read
Greedy Algorithm for Egyptian FractionEvery positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians. Following are a
11 min read
Policemen catch thievesGiven an array arr, where each element represents either a policeman (P) or a thief (T). The objective is to determine the maximum number of thieves that can be caught under the following conditions:Each policeman (P) can catch only one thief (T).A policeman can only catch a thief if the distance be
12 min read
Fitting Shelves ProblemGiven length of wall w and shelves of two lengths m and n, find the number of each type of shelf to be used and the remaining empty space in the optimal solution so that the empty space is minimum. The larger of the two shelves is cheaper so it is preferred. However cost is secondary and first prior
9 min read
Assign Mice to HolesThere are N Mice and N holes are placed in a straight line. Each hole can accommodate only 1 mouse. A mouse can stay at his position, move one step right from x to x + 1, or move one step left from x to x -1. Any of these moves consumes 1 minute. Assign mice to holes so that the time when the last m
8 min read
Greedy algorithm on Array
Minimum product subset of an arrayINTRODUCTION: The minimum product subset of an array refers to a subset of elements from the array such that the product of the elements in the subset is minimized. To find the minimum product subset, various algorithms can be used, such as greedy algorithms, dynamic programming, and branch and boun
13 min read
Maximize array sum after K negations using SortingGiven an array of size n and an integer k. We must modify array k number of times. In each modification, we can replace any array element arr[i] by -arr[i]. The task is to perform this operation in such a way that after k operations, the sum of the array is maximum.Examples : Input : arr[] = [-2, 0,
10 min read
Minimum sum of product of two arraysFind the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.Examples: Input : a[] = {1, 2, -3} b[] = {-2, 3, -5} k = 5 Output : -31 Exp
14 min read
Minimum sum of absolute difference of pairs of two arraysGiven two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
7 min read
Minimum increment/decrement to make array non-IncreasingGiven an array a, your task is to convert it into a non-increasing form such that we can either increment or decrement the array value by 1 in the minimum changes possible. Examples : Input : a[] = {3, 1, 2, 1}Output : 1Explanation : We can convert the array into 3 1 1 1 by changing 3rd element of a
11 min read
Sorting array with reverse around middleConsider the given array arr[], we need to find if we can sort array with the given operation. The operation is We have to select a subarray from the given array such that the middle element(or elements (in case of even number of elements)) of subarray is also the middle element(or elements (in case
6 min read
Sum of Areas of Rectangles possible for an arrayGiven an array, the task is to compute the sum of all possible maximum area rectangles which can be formed from the array elements. Also, you can reduce the elements of the array by at most 1. Examples: Input: a = {10, 10, 10, 10, 11, 10, 11, 10} Output: 210 Explanation: We can form two rectangles o
13 min read
Largest lexicographic array with at-most K consecutive swapsGiven an array arr[], find the lexicographically largest array that can be obtained by performing at-most k consecutive swaps. Examples : Input : arr[] = {3, 5, 4, 1, 2} k = 3 Output : 5, 4, 3, 2, 1 Explanation : Array given : 3 5 4 1 2 After swap 1 : 5 3 4 1 2 After swap 2 : 5 4 3 1 2 After swap 3
9 min read
Partition into two subsets of lengths K and (N - k) such that the difference of sums is maximumGiven an array of non-negative integers of length N and an integer K. Partition the given array into two subsets of length K and N - K so that the difference between the sum of both subsets is maximum. Examples : Input : arr[] = {8, 4, 5, 2, 10} k = 2 Output : 17 Explanation : Here, we can make firs
7 min read
Greedy algorithm on Operating System
Program for First Fit algorithm in Memory ManagementPrerequisite : Partition Allocation MethodsIn the first fit, the partition is allocated which is first sufficient from the top of Main Memory.Example : Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426};Output:Process No. Process Size Block no. 1 212 2 2 417 5 3 11
8 min read
Program for Best Fit algorithm in Memory ManagementPrerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Bl
8 min read
Program for Worst Fit algorithm in Memory ManagementPrerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it. Example: Input : blo
8 min read
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)The shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN, also known as Shortest Job Next (SJN), can be preemptive or non-preemptive. Â Characteristics of SJF Scheduling: Shortest Job first has th
13 min read
Job Scheduling with two jobs allowed at a timeGiven a 2d array jobs[][] of order n * 2, where each element jobs[i], contains two integers, representing the start and end time of the job. Your task is to check if it is possible to complete all the jobs, provided that two jobs can be done simultaneously at a particular moment. Note: If a job star
6 min read
Optimal Page Replacement AlgorithmIn operating systems, whenever a new page is referred and not present in memory, page fault occurs, and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorit
3 min read
Greedy algorithm on Graph