Problem
Given an undirected graph and a number m (m colors), determine if the graph can be colored with at most m colors such that no two adjacent vertices are colored with the same color. Coloring means assigning a color to each vertex.
OR
Given an undirected graph represented as an adjacency matrix and an integer k, write a function to determine whether each vertex in the graph can be colored such that no two adjacent vertices share the same color using at most k colors.
Input Format
n
: Number of vertices (integer)edges
: List of edges, where each edge is represented as a pair[u, v]
indicating an undirected edge between vertexu
and vertexv
(0-based indexing)m
: Maximum number of colors (integer)
Examples
Example 1
graph TB; subgraph I["Input"] 0(0)--- 1(1) & 2(2) & 3(3) 1 --- 2 2 --- 3 end subgraph O["Output"]; A(0) --- B(1) & C(2) & D(3) B --- C C --- D end I ~~~ O style A fill:#FF9933 style B fill:#3399FF style D fill:#3399FF style C fill:#99FF33
|
|
Solution
Solution
Method 1 – Brute Force (Naive)
Intuition
Try all possible ways to assign m colors to n vertices, and check if any assignment is valid (no two adjacent vertices share the same color).
Approach
- Generate all possible assignments of m colors to n vertices (there are m^n possible assignments).
- For each assignment, check all edges in the
edges
list:- For each edge [u, v], check if the colors assigned to u and v are different.
- If a valid coloring is found, return true; otherwise, return false.
Complexity
- ⏰ Time complexity:
O(m^n * n^2)
(orO(m^n * E)
), where n is the number of vertices and E is the number of edges. For each of the m^n assignments, we check all edges. - 🧺 Space complexity:
O(n)
, for storing a coloring assignment.
Method 2 – Backtracking
Intuition
Assign colors to vertices one by one, backtracking if a conflict is found, to efficiently search for a valid coloring.
Approach
- Start from the first vertex.
- For each color from 1 to m:
- Check if assigning this color to the current vertex is safe (no adjacent vertex has the same color).
- If safe, assign the color and move to the next vertex recursively.
- If not, try the next color.
- If all vertices are assigned, return the coloring; otherwise, backtrack.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^m)
, wheren
is the number of vertices in the graph andm
is the maximum number of colors allowed (which can be as high as the number of vertices in the worst case).- In the worst case, the algorithm might try coloring each vertex with all possible colors and backtrack if a conflict arises. This can lead to an exponential number of possibilities, resulting in a time complexity of O(n^m),
- 🧺 Space complexity:
O(n)