Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Introduction to Graph Coloring
Next article icon

Introduction to Graph Coloring

Last Updated : 02 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Graph coloring refers to the problem of coloring vertices of a graph in such a way that no two adjacent vertices have the same color. This is also called the vertex coloring problem. If coloring is done using at most m colors, it is called m-coloring.

Graph-Coloring-copy

Chromatic Number:

The minimum number of colors needed to color a graph is called its chromatic number. For example, the following can be colored a minimum of 2 colors.

chromatic-number-of-cycle-graph-example
Example of Chromatic Number

The problem of finding a chromatic number of a given graph is NP-complete.

Graph coloring problem is both, a decision problem as well as an optimization problem.

  • A decision problem is stated as, "With given M colors and graph G, whether a such color scheme is possible or not?".
  • The optimization problem is stated as, "Given M colors and graph G, find the minimum number of colors required for graph coloring."

Algorithm of Graph Coloring using Backtracking:

Assign colors one by one to different vertices, starting from vertex 0. Before assigning a color, check if the adjacent vertices have the same color or not. If there is any color assignment that does not violate the conditions, mark the color assignment as part of the solution. If no assignment of color is possible then backtrack and return false.

Follow the given steps to solve the problem:

  • Create a recursive function that takes the graph, current index, number of vertices, and color array.
  • If the current index is equal to the number of vertices. Print the color configuration in the color array.
  • Assign a color to a vertex from the range (1 to m).
    • For every assigned color, check if the configuration is safe, (i.e. check if the adjacent vertices do not have the same color) and recursively call the function with the next index and number of vertices else return false
    • If any recursive function returns true then break the loop and return true
    • If no recursive function returns true then return false

Below is the implementation of the above approach:

C++
// C++ program for solution of M // Coloring problem using backtracking  #include <bits/stdc++.h> using namespace std;  // Number of vertices in the graph #define V 4  void printSolution(int color[]);  /* A utility function to check if    the current color assignment    is safe for vertex v i.e. checks    whether the edge exists or not    (i.e, graph[v][i]==1). If exist    then checks whether the color to    be filled in the new vertex(c is    sent in the parameter) is already    used by its adjacent    vertices(i-->adj vertices) or    not (i.e, color[i]==c) */ bool isSafe(int v, bool graph[V][V], int color[], int c) {     for (int i = 0; i < V; i++)         if (graph[v][i] && c == color[i])             return false;      return true; }  /* A recursive utility function to solve m coloring problem */ bool graphColoringUtil(bool graph[V][V], int m, int color[],                        int v) {      /* base case: If all vertices are        assigned a color then return true */     if (v == V)         return true;      /* Consider this vertex v and        try different colors */     for (int c = 1; c <= m; c++) {          /* Check if assignment of color            c to v is fine*/         if (isSafe(v, graph, color, c)) {             color[v] = c;              /* recur to assign colors to                rest of the vertices */             if (graphColoringUtil(graph, m, color, v + 1)                 == true)                 return true;              /* If assigning color c doesn't                lead to a solution then remove it */             color[v] = 0;         }     }      /* If no color can be assigned to        this vertex then return false */     return false; }  /* This function solves the m Coloring    problem using Backtracking. It mainly    uses graphColoringUtil() to solve the    problem. It returns false if the m    colors cannot be assigned, otherwise    return true and prints assignments of    colors to all vertices. Please note    that there may be more than one solutions,    this function prints one of the    feasible solutions.*/ bool graphColoring(bool graph[V][V], int m) {      // Initialize all color values as 0.     // This initialization is needed     // correct functioning of isSafe()     int color[V];     for (int i = 0; i < V; i++)         color[i] = 0;      // Call graphColoringUtil() for vertex 0     if (graphColoringUtil(graph, m, color, 0) == false) {         cout << "Solution does not exist";         return false;     }      // Print the solution     printSolution(color);     return true; }  /* A utility function to print solution */ void printSolution(int color[]) {     cout << "Solution Exists:"          << " Following are the assigned colors"          << "\n";     for (int i = 0; i < V; i++)         cout << " " << color[i] << " ";      cout << "\n"; }  // Driver code int main() {      /* Create following graph and test        whether it is 3 colorable       (3)---(2)        |   / |        |  /  |        | /   |       (0)---(1)     */     bool graph[V][V] = {         { 0, 1, 1, 1 },         { 1, 0, 1, 0 },         { 1, 1, 0, 1 },         { 1, 0, 1, 0 },     };      // Number of colors     int m = 3;      // Function call     graphColoring(graph, m);     return 0; } 
Java
// Nikunj Sonigara  public class Main {      static final int V = 4;      // A utility function to check if the current color assignment is safe for vertex v     static boolean isSafe(int v, boolean[][] graph, int[] color, int c) {         for (int i = 0; i < V; i++)             if (graph[v][i] && c == color[i])                 return false;         return true;     }      // A recursive utility function to solve m coloring problem     static boolean graphColoringUtil(boolean[][] graph, int m, int[] color, int v) {         if (v == V)             return true;          for (int c = 1; c <= m; c++) {             if (isSafe(v, graph, color, c)) {                 color[v] = c;                 if (graphColoringUtil(graph, m, color, v + 1))                     return true;                 color[v] = 0;             }         }          return false;     }      // This function solves the m Coloring problem using Backtracking.     // It returns false if the m colors cannot be assigned, otherwise, return true     // and prints assignments of colors to all vertices.     static boolean graphColoring(boolean[][] graph, int m) {         int[] color = new int[V];         for (int i = 0; i < V; i++)             color[i] = 0;          if (!graphColoringUtil(graph, m, color, 0)) {             System.out.println("Solution does not exist");             return false;         }          // Print the solution         printSolution(color);         return true;     }      // A utility function to print the solution     static void printSolution(int[] color) {         System.out.print("Solution Exists: Following are the assigned colors\n");         for (int i = 0; i < V; i++)             System.out.print(" " + color[i] + " ");         System.out.println();     }      // Driver code     public static void main(String[] args) {         // Create following graph and test whether it is 3 colorable         // (3)---(2)         // |   / |         // |  /  |         // | /   |         // (0)---(1)          boolean[][] graph = {             { false, true, true, true },             { true, false, true, false },             { true, true, false, true },             { true, false, true, false }         };          // Number of colors         int m = 3;          // Function call         graphColoring(graph, m);     } } 
Python3
V = 4  def print_solution(color):     print("Solution Exists: Following are the assigned colors")     print(" ".join(map(str, color)))  def is_safe(v, graph, color, c):     # Check if the color 'c' is safe for the vertex 'v'     for i in range(V):         if graph[v][i] and c == color[i]:             return False     return True  def graph_coloring_util(graph, m, color, v):     # Base case: If all vertices are assigned a color, return true     if v == V:         return True      # Try different colors for the current vertex 'v'     for c in range(1, m + 1):         # Check if assignment of color 'c' to 'v' is fine         if is_safe(v, graph, color, c):             color[v] = c              # Recur to assign colors to the rest of the vertices             if graph_coloring_util(graph, m, color, v + 1):                 return True              # If assigning color 'c' doesn't lead to a solution, remove it             color[v] = 0      # If no color can be assigned to this vertex, return false     return False  def graph_coloring(graph, m):     color = [0] * V      # Call graph_coloring_util() for vertex 0     if not graph_coloring_util(graph, m, color, 0):         print("Solution does not exist")         return False      # Print the solution     print_solution(color)     return True  # Driver code if __name__ == "__main__":     graph = [         [0, 1, 1, 1],         [1, 0, 1, 0],         [1, 1, 0, 1],         [1, 0, 1, 0],     ]      m = 3      # Function call     graph_coloring(graph, m)          #This code is contrubting by Raja Ramakrishna 
C#
using System;  class GraphColoringProblem {     // Number of vertices in the graph     const int V = 4;      // A utility function to check if the current color assignment is safe for vertex v     static bool IsSafe(int v, bool[,] graph, int[] color, int c)     {         for (int i = 0; i < V; i++)         {             if (graph[v, i] && c == color[i])                 return false;         }         return true;     }      // A recursive utility function to solve m coloring problem     static bool GraphColoringUtil(bool[,] graph, int m, int[] color, int v)     {         if (v == V)             return true;          for (int c = 1; c <= m; c++)         {             if (IsSafe(v, graph, color, c))             {                 color[v] = c;                  if (GraphColoringUtil(graph, m, color, v + 1))                     return true;                  color[v] = 0;             }         }         return false;     }      // This function solves the m Coloring problem using Backtracking     static bool SolveGraphColoring(bool[,] graph, int m)     {         int[] color = new int[V];         for (int i = 0; i < V; i++)             color[i] = 0;          if (!GraphColoringUtil(graph, m, color, 0))         {             Console.WriteLine("Solution does not exist");             return false;         }          PrintSolution(color);         return true;     }      // A utility function to print solution     static void PrintSolution(int[] color)     {         Console.WriteLine("Solution Exists: Following are the assigned colors");         for (int i = 0; i < V; i++)             Console.Write(" " + color[i] + " ");         Console.WriteLine();     }      // Driver code     static void Main(string[] args)     {         /* Create following graph and test whether it is 3 colorable            (3)---(2)             |   / |             |  /  |             | /   |            (0)---(1)         */         bool[,] graph = {             { false, true, true, true },             { true, false, true, false },             { true, true, false, true },             { true, false, true, false }         };          // Number of colors         int m = 3;          // Function call         SolveGraphColoring(graph, m);     } }   // This code is contributed by shivamgupta310570 
JavaScript
// Equivalent JavaScript program for M Coloring problem using backtracking  // Number of vertices in the graph const V = 4;  // Function to print the solution function printSolution(color) {     console.log("Solution Exists: Following are the assigned colors");     for (let i = 0; i < V; i++) {         console.log(color[i] + " ");     }     console.log("\n"); }  // Utility function to check if the current color assignment is safe for the vertex function isSafe(v, graph, color, c) {     for (let i = 0; i < V; i++) {         if (graph[v][i] && c == color[i]) {             return false;         }     }     return true; }  // Recursive utility function to solve the M coloring problem function graphColoringUtil(graph, m, color, v) {     // Base case: If all vertices are assigned a color, return true     if (v === V) {         return true;     }      // Consider the vertex v and try different colors     for (let c = 1; c <= m; c++) {         // Check if assignment of color c to v is fine         if (isSafe(v, graph, color, c)) {             color[v] = c;              // Recur to assign colors to the rest of the vertices             if (graphColoringUtil(graph, m, color, v + 1)) {                 return true;             }              // If assigning color c doesn't lead to a solution, remove it             color[v] = 0;         }     }      // If no color can be assigned to this vertex, return false     return false; }  // Function to solve the M Coloring problem using backtracking function graphColoring(graph, m) {     // Initialize all color values as 0     const color = new Array(V).fill(0);      // Call graphColoringUtil() for vertex 0     if (!graphColoringUtil(graph, m, color, 0)) {         console.log("Solution does not exist");         return false;     }      // Print the solution     printSolution(color);     return true; }  // Driver code const graph = [     [0, 1, 1, 1],     [1, 0, 1, 0],     [1, 1, 0, 1],     [1, 0, 1, 0], ];  const m = 3;  // Function call graphColoring(graph, m);  // This code is contributed by shivamgupta310570 

Output
Solution Exists: Following are the assigned colors  1  2  3  2  

Applications of Graph Coloring:

  • Design a timetable.
  • Sudoku.
  • Register allocation in the compiler.
  • Map coloring.
  • Mobile radio frequency assignment.

Related Articles:

  • Graph Coloring Using Greedy Algorithm
  • M-Coloring Problem
  • Edge Coloring of a Graph

Next Article
Introduction to Graph Coloring

K

kartik
Improve
Article Tags :
  • Graph
  • DSA
  • Graph Coloring
Practice Tags :
  • Graph

Similar Reads

    Graph Algorithms
    Graph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
    3 min read
    Introduction to Graph Data Structure
    Graph Data Structure is a non-linear data structure consisting of vertices and edges. It is useful in fields such as social network analysis, recommendation systems, and computer networks. In the field of sports data science, graph data structure can be used to analyze and understand the dynamics of
    15+ min read
    Graph and its representations
    A Graph is a non-linear data structure consisting of vertices and edges. The vertices are sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is den
    12 min read
    Types of Graphs with Examples
    A graph is a mathematical structure that represents relationships between objects by connecting a set of points. It is used to establish a pairwise relationship between elements in a given set. graphs are widely used in discrete mathematics, computer science, and network theory to represent relation
    9 min read
    Basic Properties of a Graph
    A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. The basic properties of a graph include: Vertices (nodes): The points where edges meet in a graph are kn
    4 min read
    Applications, Advantages and Disadvantages of Graph
    Graph is a non-linear data structure that contains nodes (vertices) and edges. A graph is a collection of set of vertices and edges (formed by connecting two vertices). A graph is defined as G = {V, E} where V is the set of vertices and E is the set of edges. Graphs can be used to model a wide varie
    7 min read
    Transpose graph
    Transpose of a directed graph G is another directed graph on the same set of vertices with all of the edges reversed compared to the orientation of the corresponding edges in G. That is, if G contains an edge (u, v) then the converse/transpose/reverse of G contains an edge (v, u) and vice versa. Giv
    9 min read
    Difference Between Graph and Tree
    Graphs and trees are two fundamental data structures used in computer science to represent relationships between objects. While they share some similarities, they also have distinct differences that make them suitable for different applications. Difference Between Graph and Tree What is Graph?A grap
    2 min read

    BFS and DFS on Graph

    Breadth First Search or BFS for a Graph
    Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
    15+ min read
    Depth First Search or DFS for a Graph
    In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
    13 min read
    Applications, Advantages and Disadvantages of Depth First Search (DFS)
    Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
    4 min read
    Applications, Advantages and Disadvantages of Breadth First Search (BFS)
    We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweight
    4 min read
    Iterative Depth First Traversal of Graph
    Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
    10 min read
    BFS for Disconnected Graph
    In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, s
    14 min read
    Transitive Closure of a Graph using DFS
    Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
    8 min read
    Difference between BFS and DFS
    Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
    2 min read

    Cycle in a Graph

    Detect Cycle in a Directed Graph
    Given the number of vertices V and a list of directed edges, determine whether the graph contains a cycle or not.Examples: Input: V = 4, edges[][] = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]]Cycle: 0 → 2 → 0 Output: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 0 Input: V = 4, edges[][] =
    15+ min read
    Detect cycle in an undirected graph
    Given an undirected graph, the task is to check if there is a cycle in the given graph.Examples:Input: V = 4, edges[][]= [[0, 1], [0, 2], [1, 2], [2, 3]]Undirected Graph with 4 vertices and 4 edgesOutput: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0Input: V = 4, edges[][] = [[0,
    8 min read
    Detect Cycle in a directed graph using colors
    Given a directed graph represented by the number of vertices V and a list of directed edges, determine whether the graph contains a cycle.Your task is to implement a function that accepts V (number of vertices) and edges (an array of directed edges where each edge is a pair [u, v]), and returns true
    9 min read
    Detect a negative cycle in a Graph | (Bellman Ford)
    Given a directed weighted graph, your task is to find whether the given graph contains any negative cycles that are reachable from the source vertex (e.g., node 0).Note: A negative-weight cycle is a cycle in a graph whose edges sum to a negative value.Example:Input: V = 4, edges[][] = [[0, 3, 6], [1
    15+ min read
    Cycles of length n in an undirected and connected graph
    Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardle
    10 min read
    Detecting negative cycle using Floyd Warshall
    We are given a directed graph. We need compute whether the graph has negative cycle or not. A negative cycle is one in which the overall sum of the cycle comes negative. Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some adva
    12 min read
    Clone a Directed Acyclic Graph
    A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences