VOOZH about

URL: https://www.geeksforgeeks.org/dsa/m-coloring-problem/

⇱ M-Coloring Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

M-Coloring Problem

Last Updated : 23 Jul, 2025

Given an edges of graph and a number m, the your task is to check it is possible to color the given graph with at most m colors such that no two adjacent vertices of the graph are colored with the same color.

Examples

Input: V = 4, edges[][] = [[0, 1], [0, 2], [0,3], [1, 3], [2, 3]], m = 3
Output: true
Explanation: Structure allows enough separation between connected vertices, so using 3 colors is sufficient to ensure no two adjacent vertices share the same color—hence, the answer is true

👁 M-Coloring-Problem-2

Input:  V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 4], [2, 3], [2, 4], [3, 4]], m = 3
Output: false
Explanation: In this graph, the vertices are highly interconnected, especially vertex 2, which connects to four others. With only 3 colors, it's impossible to assign colors so that no two adjacent vertices share the same color, hence, the answer is false.

Approach 1: Generate all possible configurations - O((V + E)*m^V) Time and O(E+V) Space

Generate all possible configurations of length V of colors. Since each node can be colored using any of the m available colors, the total number of color configurations possible is mV. After generating a configuration of color, check if the adjacent vertices have the same color or not. If the conditions are met, print the combination.


Output
true

Approach 2: Using Backtracking - O(V * m^V) Time and O(V+E) Space

Assign colors one by one to different vertices, starting from vertex 0. Before assigning a color, check for safety by considering already assigned colors to the adjacent vertices i.e 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

Illustration:


Output
true

Time Complexity: O(V * mV). There is a total of O(mV) combinations of colors. For each attempted coloring of a vertex you call issafe(), can have up to V–1 neighbors, so issafe() is O(V)
Auxiliary Space: O(V + E). The recursive Stack of the graph coloring function will require O(V) space, Adjacency list and color array will required O(V+E).


Comment