import sys
def greedy_coloring(graph, ordering=None):
"""
Greedy graph coloring algorithm to assign colors to vertices such that no adjacent vertices
share the same color. Uses the smallest possible color for each vertex.
Args:
- graph: List of lists representing the adjacency list (undirected graph).
Vertices are numbered 0 to n-1.
- ordering: List of vertex indices in the order to color them (optional).
If None, uses natural order (0 to n-1).
Returns:
- colors: List of length n, where colors[i] is the color assigned to vertex i (0-based).
- num_colors: Number of distinct colors used (chromatic number approximation).
This is a heuristic; it minimizes colors approximately. For exact minimization, use backtracking
(exponential time, see backtracking_coloring below).
"""
n = len(graph)
if ordering is None:
ordering = list(range(n))
colors = [-1] * n
for i in range(n):
v = ordering[i]
used = set()
for nei in graph[v]:
if colors[nei] != -1:
used.add(colors[nei])
col = 0
while col in used:
col += 1
colors[v] = col
num_colors = max(colors) + 1 if n > 0 else 0
return colors, num_colors
def degree_ordering(graph):
"""Returns vertex ordering by decreasing degree (Welsh-Powell heuristic for better results)."""
n = len(graph)
degrees = [(len(graph[i]), i) for i in range(n)]
degrees.sort(reverse=True) # Highest degree first
return [i for _, i in degrees]
def backtracking_coloring(graph, max_colors=None):
"""
Exact graph coloring using backtracking to find the minimum number of colors.
Tries colors from 1 upwards until a valid coloring is found.
Args:
- graph: Adjacency list.
- max_colors: Upper bound on colors to try (optional; defaults to n).
Returns:
- colors: List of colors if successful, None otherwise.
- num_colors: Minimum number of colors used.
WARNING: Exponential time; suitable only for small graphs (n <= 30 typically).
"""
n = len(graph)
if max_colors is None:
max_colors = n
colors = [-1] * n
def is_safe(v, c):
for nei in graph[v]:
if colors[nei] == c:
return False
return True
def color_util(v):
if v == n:
return True # All vertices colored
for c in range(max_colors):
if is_safe(v, c):
colors[v] = c
if color_util(v + 1):
return True
colors[v] = -1 # Backtrack
return False
# Try increasing number of colors until success
for num_colors in range(1, max_colors + 1):
colors = [-1] * n
if color_util(0):
return colors, num_colors
return None, None
# Example usage
if __name__ == "__main__":
# Example 1: Triangle (complete graph K3, chromatic number 3)
graph1 = [
[1, 2], # Vertex 0
[0, 2], # Vertex 1
[0, 1] # Vertex 2
]
colors_greedy, num_greedy = greedy_coloring(graph1, degree_ordering(graph1))
print("Triangle (Greedy with degree ordering):")
print(f"Colors: {colors_greedy}, Colors used: {num_greedy}")
colors_exact, num_exact = backtracking_coloring(graph1)
print(f"Exact: Colors: {colors_exact}, Colors used: {num_exact}\n")
# Example 2: Bipartite graph (cycle of 4, chromatic number 2)
graph2 = [
[1, 3], # 0
[0, 2], # 1
[1, 3], # 2
[0, 2] # 3
]
colors_greedy2, num_greedy2 = greedy_coloring(graph2)
print("C4 (Greedy natural order):")
print(f"Colors: {colors_greedy2}, Colors used: {num_greedy2}")
# To read from stdin: n m, then m edges (0-based)
# Example input:
# 4 4
# 0 1
# 1 2
# 2 3
# 3 0
Explanation
Greedy Coloring: Fast O(n + m) heuristic. Processes vertices in a given order, assigning the lowest valid color. Use degree_ordering for better approximation (often close to optimal).
Backtracking: Exact solver that finds the true minimum colors but is slow for large graphs.
Minimizing Colors: Greedy gives ≤ Δ+1 colors (Δ = max degree). Backtracking guarantees minimum but use sparingly.
Input/Output: Adjacency list format. Colors are 0-indexed integers starting from 0.
Elementary, my dear coder. Run the script for examples, or modify graph for your own!