The user wants a graph coloring algorithm implementation.
The goal is to minimize color usage. This implies finding the chromatic number or getting close to it.
Graph coloring is an NP-hard problem, so finding the exact minimum (chromatic number) for large graphs is computationally infeasible in polynomial time.
Therefore, I should provide:
- Greedy Algorithm: A fast, standard heuristic (like Welsh-Powell or DSATUR) that gives a decent approximation.
- Exact Algorithm (Backtracking): An algorithm that guarantees the minimum number of colors but is slow. Good for small graphs.
- Explanation: Briefly explain how they work and the trade-offs.
Let's start with the Greedy approach. The simplest is just iterating through nodes and assigning the first available color. A better heuristic is Welsh-Powell (ordering nodes by degree descending) or DSATUR (ordering by saturation degree). DSATUR is generally better for minimizing colors but slightly more complex to implement. Let's stick to a well-implemented Greedy approach (like ordering by degree) and a Backtracking approach for the "exact" solution.
Algorithm 1: Greedy Coloring (Heuristic)
- Input: Adjacency list or matrix.
- Ordering: Sort vertices by degree (descending) usually yields better results.
- Process:
- For each vertex v in sorted order:
- Find colors used by neighbors of v.
- Assign the smallest positive integer (color) not used by neighbors.
Algorithm 2: Backtracking (Exact)
- Input: Graph, number of colors k (we can binary search k or increment it).
- Process:
- Try to color vertex 0 with color 1.
- Check if safe (no neighbor has same color).
- If safe, recurse for vertex 1.
- If not safe, try next color.
- If no color works, backtrack.
- To minimize, start with k=1, if impossible, k=2, etc. Or binary search between 1 and ∣V∣.
Implementation Details:
I'll use Python. It's readable and commonly used for algorithms.
- Data Structure: A
Graph class or just functions taking adjacency lists. Let's use an adjacency list defaultdict(list) or a simple list of lists.
Drafting the Greedy Code:
def greedy_coloring(graph):
# graph is dict: {node: [neighbors]}
# Sort nodes by degree descending for better result
nodes = sorted(graph.keys(), key=lambda x: len(graph[x]), reverse=True)
color_map = {}
for node in nodes:
neighbor_colors = set()
for neighbor in graph[node]:
if neighbor in color_map:
neighbor_colors.add(color_map[neighbor])
# Find first available color
color = 1
while color in neighbor_colors:
color += 1
color_map[node] = color
return color_map
Drafting the Backtracking Code:
To truly minimize, we iterate k from 1 upwards.
def is_safe(node, color, graph, colors):
for neighbor in graph[node]:
if colors[neighbor] == color:
return False
return True
def solve(node, graph, colors, k):
if node == len(graph): return True # All colored
for color in range(1, k + 1):
if is_safe(node, color, graph, colors):
colors[node] = color
if solve(node + 1, graph, colors, k):
return True
colors[node] = 0 # Backtrack
return False
def exact_coloring(graph):
# Try k = 1, 2, ...
# Note: need to map graph nodes to 0..N-1 indices for easy array access
pass
Refining the Backtracking Logic:
The naive backtracking is O(NM). There are optimizations (MRV - Minimum Remaining Values), but for a "standard" implementation request, simple backtracking is sufficient to demonstrate the concept of finding the exact minimum, with a caveat about performance.
Putting it together:
I will provide a Python class Graph that contains both methods.
greedy_coloring: Fast, approximate.
backtracking_coloring: Slow, exact minimum.
I should also include a helper to verify the coloring and calculate the number of colors used.
Edge Cases:
- Empty graph.
- Disconnected graph.
- Node labels that aren't 0-indexed integers (handle mapping).
Let's write the code clearly with comments.
Plan:
- Define a
Graph class.
- Implement
greedy_coloring (heuristic, O(V+E) approx).
- Implement
backtracking_coloring (exact, exponential time).
- Provide an example usage block.
- Briefly explain the time complexity and the difference between the two approaches.
Self-Correction on Greedy:
Simple greedy (iterating 0 to N) is very dependent on input order. Degree-based ordering (Welsh-Powell) is much better at minimizing colors. I will implement degree-based ordering.
Self-Correction on Backtracking:
To minimize colors, we assume the graph uses k colors. We start k=1 and increment. If solve(k) returns true, that's the minimum.
Let's verify the implementation details.
Nodes might be strings or arbitrary IDs. Using a mapping node_to_idx and idx_to_node makes array-based backtracking easier.
Final Structure of the response:
- Introduction: Mention NP-hardness.
- Approach 1: Greedy Heuristic (Welsh-Powell variation): Good for large graphs.
- Approach 2: Backtracking (Exact): Good for small graphs to find absolute minimum.
- Code: Single Python script with both.
- Example: Create a graph (e.g., Petersen or a simple cycle) and run both.
Let's write the actual code mentally.
class Graph:
def __init__(self, nodes):
self.nodes = nodes
self.adj = {n: [] for n in nodes}
def add_edge(self, u, v):
self.adj[u].append(v)
self.adj[v].append(u)
# Greedy
def greedy_coloring(self):
# order by degree descending
sorted_nodes = sorted(self.nodes, key=lambda x: len(self.adj[x]), reverse=True)
result = {}
for node in sorted_nodes:
# set of neighbor colors
used = {result[nb] for nb in self.adj[node] if nb in result}
# find smallest positive not in used
color = 1
while color in used:
color += 1
result[node] = color
return result
# Backtracking
def exact_coloring(self):
# ... logic to try k colors ...
pass
This looks solid. I will present this solution.
Graph coloring is an NP-hard problem, meaning there is no known algorithm to find the absolute minimum number of colors (the chromatic number) for any graph in polynomial time.
However, we can implement two approaches depending on the graph size:
- Greedy Heuristic (Welsh-Powell): Fast (O(V2)), efficient, and finds a "local minimum" suitable for large graphs.
- Backtracking with Pruning: Guaranteed to find the absolute minimum (chromatic number), but slow (exponential time), suitable only for small graphs.
Below is a Python implementation that includes both strategies.
Python Implementation
import networkx as nx
from collections import defaultdict
class GraphColoringSolver:
def __init__(self, graph):
"""
Initialize with a NetworkX graph object.
"""
self.graph = graph
self.nodes = list(graph.nodes())
self.num_nodes = len(self.nodes)
# Map node labels to integer indices for easier array manipulation
self.node_to_idx = {node: i for i, node in enumerate(self.nodes)}
self.idx_to_node = {i: node for i, node in enumerate(self.nodes)}
# Build adjacency list using integer indices
self.adj_list = defaultdict(set)
for u, v in graph.edges():
u_idx, v_idx = self.node_to_idx[u], self.node_to_idx[v]
self.adj_list[u_idx].add(v_idx)
self.adj_list[v_idx].add(u_idx)
def is_safe(self, node_idx, color_idx, current_colors):
"""
Check if 'color_idx' can be assigned to 'node_idx'
without conflicting with neighbors.
"""
for neighbor in self.adj_list[node_idx]:
if current_colors[neighbor] == color_idx:
return False
return True
# --- Strategy 1: Greedy Heuristic (Welsh-Powell) ---
def solve_greedy(self):
"""
Orders nodes by descending degree and assigns the first available color.
Fast, but not guaranteed to be optimal.
"""
# Sort nodes by degree (number of connections) descending
# This heuristic reduces the number of colors used significantly
sorted_nodes = sorted(self.nodes, key=lambda x: self.graph.degree(x), reverse=True)
# Dictionary to store final colors: {NodeLabel: ColorInt}
color_map = {}
# Since we use integers for colors, we can just iterate 1, 2, 3...
current_color = 0
while len(color_map) < self.num_nodes:
current_color += 1
# Try to assign this color to nodes that aren't colored yet
for node in sorted_nodes:
if node in color_map:
continue
node_idx = self.node_to_idx[node]
# Check if any neighbor already has this color
can_color = True
for neighbor in self.graph.neighbors(node):
if color_map.get(neighbor) == current_color:
can_color = False
break
if can_color:
color_map[node] = current_color
return color_map
# --- Strategy 2: Exact Backtracking (Recursive) ---
def solve_exact(self):
"""
Uses backtracking to find the absolute minimum number of colors.
Warning: Exponential time complexity. Use only for small graphs.
"""
# Try to color the graph with m = 1, 2, 3... colors until success
for m in range(1, self.num_nodes + 1):
colors = [0] * self.num_nodes # 0 means uncolored
if self._backtrack_util(0, m, colors):
# Convert internal array back to dictionary
return {self.idx_to_node[i]: colors[i] for i in range(self.num_nodes)}
return None
def _backtrack_util(self, node_idx, max_colors, colors):
# Base case: If all nodes are colored, we are done
if node_idx == self.num_nodes:
return True
# Try different colors (1 to max_colors)
for c in range(1, max_colors + 1):
if self.is_safe(node_idx, c, colors):
colors[node_idx] = c
# Recurse for the next node
if self._backtrack_util(node_idx + 1, max_colors, colors):
return True
# Backtrack: If assigning color c doesn't lead to a solution, remove it
colors[node_idx] = 0
return False
# --- Usage Example ---
def visualize_colors(color_map):
# Simple print function to show results
print(f"Total colors used: {max(color_map.values())}")
for node, color in color_map.items():
print(f"Node {node}: Color {color}")
if __name__ == "__main__":
# 1. Create a sample graph (The Petersen Graph is a classic example)
# It has 10 nodes and chromatic number 3.
G = nx.petersen_graph()
solver = GraphColoringSolver(G)
print("--- Greedy Heuristic (Fast) ---")
greedy_solution = solver.solve_greedy()
visualize_colors(greedy_solution)
print("\n")
print("--- Exact Algorithm (Slow but Optimal) ---")
# Note: This might take a long time if you increase nodes > 20
exact_solution = solver.solve_exact()
visualize_colors(exact_solution)
How It Works
1. The Greedy Approach (solve_greedy)
This is the practical choice for real-world data.
- Logic: It iterates through a list of colors (1,2,3...). For a specific color, it tries to paint as many uncolored nodes as possible that aren't neighbors.
- Optimization: Before starting, it sorts nodes by Degree (number of edges). Coloring the most connected nodes first usually leads to using fewer colors overall.
- Complexity: O(V2+E), making it extremely fast even for thousands of nodes.
2. The Exact Approach (solve_exact)
This finds the Chromatic Number.
- Logic: It asks: "Can I color this graph with 1 color?" If no, "Can I color it with 2 colors?" It increments the color count (m) until it finds a valid configuration using Backtracking.
- Complexity: O(mV), where m is colors and V is vertices. This grows exponentially. If you have 50 nodes, this will likely hang forever. It is only provided to satisfy the requirement of "minimizing" usage strictly for small academic examples.
Which one should I use?
- Use
solve_greedy for scheduling, register allocation, or map coloring.
- Use
solve_exact only if you have a very small graph (<20 nodes) and you scientifically need the proven chromatic number.