Data Structures and Algorithms

Graph Coloring and Chromatic Number Explained

Graph coloring is a fundamental concept in graph theory where colors are assigned to the vertices of a graph such that no two adjacent vertices share the same color. This technique is widely known as the vertex coloring problem. When this coloring is achieved using no more than m distinct colors, it is referred to as m-coloring.

Chromatic Number

The chromatic number of a graph represents the smallest number of colors required to color its vertices without any two connected vertices having the same color. For instance, consider a graph that can be efficiently colored using just two colors—this implies its chromatic number is 2.

Complexity of the Chromatic Number Problem

Determining the chromatic number of a given graph is classified as an NP-complete problem. This means that no known algorithm can solve all instances of this problem efficiently (i.e., in polynomial time), making it computationally challenging for large or complex graphs.

Graph Coloring as a Decision and Optimization Problem

The graph coloring problem serves two main purposes in computational theory: it can be treated as both a decision problem and an optimization problem.

Decision Problem

The decision version of graph coloring asks:

“Given a graph G and a number M, is it possible to color the graph using no more than M colors such that no two adjacent vertices share the same color?”

Optimization Problem

The optimization version of the problem seeks to:

“Determine the minimum number of colors needed to color a given graph G so that adjacent vertices are assigned different colors.”

Graph Coloring Algorithm Using Backtracking

One of the most common approaches to solving the graph coloring problem is by using backtracking. This technique involves assigning colors to vertices one by one, beginning with the first vertex. Before assigning a color to a vertex, we check whether any of its adjacent vertices already have the same color. If a valid color assignment is found that doesn’t violate the graph coloring constraints, the algorithm proceeds. If no valid assignment exists, it backtracks and tries a different path.

Step-by-Step Approach to Solve Using Backtracking

Follow these steps to implement the graph coloring solution using backtracking:

  1. Create a recursive function that takes the graph, the current vertex index, the total number of vertices, and the color array as parameters.

  2. Check for base case:
    If the current index equals the total number of vertices, print the color configuration from the color array, as all vertices are successfully colored.

  3. Assign colors from 1 to m:
    For each vertex, try assigning a color within the range (1 to m).

  4. Validate the assignment:
    For each color choice, check if it is safe to assign (i.e., ensure no adjacent vertices share the same color). If safe, recursively call the function for the next vertex.

  5. Return on success:
    If any recursive call returns true, stop further processing, break the loop, and return true.

  6. Backtrack on failure:
    If no valid color assignment is found for the current vertex, return false and backtrack to explore alternative color assignments.

Implementation of Graph Coloring Using Backtracking

The following is the implementation of the graph coloring algorithm based on the backtracking approach explained above:

				
					// 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;
}


				
			
				
					// 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);
    }
}

				
			
				
					// 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);

				
			
				
					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)
    

				
			

Output

If a valid color configuration is found, the output will display the assigned colors for each vertex:

Solution Exists: Following are the assigned colors

1  2  3  2

Applications of Graph Coloring

Graph coloring has a wide range of real-world applications, particularly in areas where resource allocation or conflict resolution is required. Common use cases include:

  • Timetable Scheduling – Assigning time slots to avoid clashes in exams or classes.
  • Sudoku Solver – Treating each cell as a vertex and ensuring numbers don’t repeat in rows, columns, or blocks.
  • Register Allocation in Compilers – Optimizing the use of limited CPU registers during program execution.
  • Map Coloring – Ensuring neighboring regions or countries are colored differently on a map.
  • Mobile Radio Frequency Assignment – Assigning frequencies to avoid interference between adjacent towers.

FAQs

What is graph coloring?

Graph coloring is the process of assigning colors to each vertex of a graph such that no two adjacent vertices have the same color.

 

The chromatic number is the smallest number of colors needed to color a graph without any two connected vertices sharing the same color.

 

Because there’s no known efficient algorithm that solves all instances of the problem in polynomial time. Finding an optimal coloring is computationally hard.

 

The decision version asks whether a graph can be colored with M colors. The optimization version tries to find the minimum number of colors required to color the graph.

DSA, High & Low Level System Designs

Buy for 60% OFF
₹25,000.00 ₹9,999.00

Accelerate your Path to a Product based Career

Boost your career or get hired at top product-based companies by joining our expertly crafted courses. Gain practical skills and real-world knowledge to help you succeed.

Reach Out Now

If you have any queries, please fill out this form. We will surely reach out to you.

Contact Email

Reach us at the following email address.

Phone Number

You can reach us by phone as well.

+91-97737 28034

Our Location

Rohini, Sector-3, Delhi-110085

WhatsApp Icon

Master Your Interviews with Our Free Roadmap!

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.