Skip to problem
←

Graph Coloring with M Colors

Medium 0 attempts

You're given an undirected graph as an adjacency matrix, along with a budget of m colors. Decide whether every vertex can be assigned one of those m colors so that no two vertices joined by an edge end up with the same color. This is the well-known graph m-coloring decision problem, typically tackled with a backtracking search over color assignments.

Function contract

graph is a symmetric 0/1 adjacency matrix for a loop-free undirected graph. graph[u][v] = 1 means u and v share an edge; m is the available color count.

Output: Return true if every vertex can be colored using at most m colors with different colors at each edge’s endpoints; otherwise return false.

Example 1

Input
graph = [[0,1,1,1],[1,0,1,0],[1,1,0,1],[1,0,1,0]]
m = 3
Output
true

Explanation: One valid assignment to vertices 0–3 is [1,2,3,2]. Vertices 1 and 3 may share a color because they are not adjacent.

Example 2

Input
graph = [[0,1,1],[1,0,1],[1,1,0]]
m = 2
Output
false
Constraints
  • 1 <= V <= 50
  • 1 <= m <= V
  • graph is a symmetric V × V 0/1 adjacency matrix with zero diagonal.

Approach: Backtracking

Try assigning colors 1 to m to each vertex in sequence. Before assigning, check if any adjacent vertex already has the same color. If no valid color exists for a vertex, backtrack.

javascript
function introductionToGraphColoring(graph, m) {
  const n = graph.length;
  const colors = new Array(n).fill(0);
  function isSafe(v, c) {
    for (let i = 0; i < n; i++)
      if (graph[v][i] && colors[i] === c) return false;
    return true;
  }
  function solve(v) {
    if (v === n) return true;
    for (let c = 1; c <= m; c++) {
      if (isSafe(v, c)) {
        colors[v] = c;
        if (solve(v + 1)) return true;
        colors[v] = 0;
      }
    }
    return false;
  }
  return solve(0);
}

Time Complexity: Exponential. There are at most m choices per vertex, and each attempted assignment scans V neighbors. For m ≥ 2, the worst-case bound is O(V × m^V); for m = 1, at most O(V²).

Space Complexity: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript