M-Coloring Problem in Python

Last Updated : 23 Jul, 2025

M-Coloring Problem is a classic algorithmic problem which involves coloring the vertices of a graph using at most M different colors such that no two adjacent vertices share the same color. We are given a graph and an integer M, determine if it's possible to color the graph using M colors such that no two adjacent vertices have the same color. Below is the example to understand problem clearly

Examples:

Input:
graph =
{{0, 1, 1, 1},
{1, 0, 1, 0},
{1, 1, 0, 1},
{1, 0, 1, 0}}, M = 3

Output
True

Input:
graph =
{{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1}}, M = 3

Output: Solution does not exist
Explanation: No solution exits

M-Coloring Problem in Python using Backtracking:

The M coloring problem can be solved by assigning colors colors to the vertices such that no two adjacent vertices share the same color. The algorithm starts by coloring the first vertex and then recursively color each subsequent vertex. For each vertex, check each color from 1 to M to see if it is safe (i.e., the color does not conflict with any adjacent vertices' colors). If a safe color is found, assign that color to the vertex and proceed to the next vertex. If no safe color is found, backtrack by removing the previously assigned color and try the next available color. This process continues until all vertices are colored or it is determined that coloring the graph with M colors is not possible. If a solution is found, the algorithm returns the color assignments; otherwise, it returns that no solution exists.

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 otherwise, return false
  • If any recursive function returns true then return true
  • If no recursive function returns true then return false

Below is the implementation of the algorithm:

Python
# Python3 program for solution of M Coloring
# problem using backtracking


class Graph():

    def __init__(self, vertices):
        self.V = vertices
        self.graph = [[0 for column in range(vertices)]
                    for row in range(vertices)]

    # A utility function to check
    # if the current color assignment
    # is safe for vertex v
    def isSafe(self, v, colour, c):
        for i in range(self.V):
            if self.graph[v][i] == 1 and colour[i] == c:
                return False
        return True

    # A recursive utility function to solve m
    # coloring problem
    def graphColourUtil(self, m, colour, v):
        if v == self.V:
            return True

        for c in range(1, m + 1):
            if self.isSafe(v, colour, c) == True:
                colour[v] = c
                if self.graphColourUtil(m, colour, v + 1) == True:
                    return True
                colour[v] = 0

    def graphColouring(self, m):
        colour = [0] * self.V
        if self.graphColourUtil(m, colour, 0) == None:
            return False

        # Print the solution
        print("Solution exist and Following are the assigned colours:")
        for c in colour:
            print(c, end=' ')
        return True


# Driver Code
if __name__ == '__main__':
    g = Graph(4)
    g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]]
    m = 3

    # Function call
    g.graphColouring(m)

Output
True

Time Complexity: O(mV). There is a total of O(mV) combinations of colors. The upper bound time complexity remains the same but the average time taken will be less.
Auxiliary Space: O(V). The recursive Stack of the graph coloring function will require O(V) space.

Comment