VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-colors-required-to-color-a-graph/

⇱ Minimum number of colors required to color a graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of colors required to color a graph

Last Updated : 22 Jun, 2021

Given a graph with N vertices and E edges. The edges are given as U[] and V[] such that for each index i, U[i] is connected to V[i]. The task is to find the minimum number of colors needed to color the given graph.
Examples 
 

Input: N = 5, M = 6, U[] = { 1, 2, 3, 1, 2, 3 }, V[] = { 3, 3, 4, 4, 5, 5 }; 
Output:
Explanation: 
For the above graph node 1, 3, and 5 cannot have the same color. Hence the count is 3. 
 


 


Approach: 
We will keep two array count[] and colors[]. The array count[] will store the count of edges for each node and colors[] will store the colors of each node. Initialize count for every vertex to 0 and color for every vertex to 1. 
Steps: 
 

  1. Make a adjacency list for the given set of edges and keep the count of edges for each node
  2. Iterate over all nodes and insert the node in the queue Q which has no edge.
  3. While Q is not empty, do the following: 
    • Pop the element from the queue.
    • For all the nodes connected to popped node: 
      1. Decrease the count of current edge for popped node.
      2. If color of current is less than or equals to color of it's parent(the node which was popped) then, Update the color of current node = 1 + color of popped node
      3. If count is zero then insert this node in the queue Q.
  4. The maximum element in colors[] array will give the minimum number of colors required to color the given graph.


Below is the implementation of the above approach: 
 


Output: 
3

 

Time Complexity: O(N+E), where N = number of vertices and E = Number of edges
 

Comment
Article Tags:
Article Tags: