101 Logo
onenoughtone

Graph Coloring Pattern

What is the Graph Coloring Problem?

The Graph Coloring problem asks us to assign colors to each vertex of a graph such that no two adjacent vertices have the same color.

The goal is to use the minimum number of colors possible, but often we're asked if a graph can be colored using at most m colors.

Example:

Can we color a graph with 3 vertices forming a triangle using 2 colors?
Answer: No, we need at least 3 colors.

Backtracking Approach

The Graph Coloring problem can be solved using backtracking:

  1. Start with the first vertex
  2. Try assigning each available color to the vertex
  3. Check if the color assignment is valid (no adjacent vertices have the same color)
  4. If valid, recursively color the next vertex
  5. If the recursive call fails, backtrack and try a different color
  6. If all colors have been tried and none work, backtrack to the previous vertex

Implementation

Here's how we can implement the Graph Coloring solution using backtracking:

function graphColoring(graph, m) { const n = graph.length; // Number of vertices const colors = Array(n).fill(0); // Color of each vertex (0 means uncolored) // Try to color the graph starting from vertex 0 if (colorGraph(0)) { return colors; } // No valid coloring found return null; function colorGraph(vertex) { // Base case: all vertices are colored if (vertex === n) { return true; } // Try each color for the current vertex for (let color = 1; color <= m; color++) { // Check if it's safe to color the vertex with this color if (isSafe(vertex, color)) { // Assign the color colors[vertex] = color; // Recursively color the rest of the graph if (colorGraph(vertex + 1)) { return true; } // Backtrack: remove the color if it doesn't lead to a solution colors[vertex] = 0; } } // No valid coloring found for this vertex return false; } function isSafe(vertex, color) { // Check if any adjacent vertex has the same color for (let i = 0; i < n; i++) { if (graph[vertex][i] === 1 && colors[i] === color) { return false; } } // The color is safe to use return true; } }

Time and Space Complexity

Time Complexity:

O(m^n), where m is the number of colors and n is the number of vertices. In the worst case, we need to try all possible color combinations.

Space Complexity:

O(n) for the colors array and the recursion stack.

IntroVisualizePatternsPractice
101 Logo
onenoughtone