Skip to content

Commit cf92959

Browse files
committed
Add Graph Colouring algorithm with Backtracking
1 parent 677abba commit cf92959

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

graphs/graph_colouring.py

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
Graph Coloring Problem is a classic problem in graph theory.
3+
The task is to assign colors to the vertices of a graph so that no two adjacent vertices
4+
share the same color, and the number of colors used is minimized.
5+
6+
Wikipedia: https://en.wikipedia.org/wiki/Graph_coloring
7+
"""
8+
9+
10+
def is_safe(graph: list[list[int]], color: list[int], v: int, c: int) -> bool:
11+
"""
12+
Helper function to check if it is safe to color vertex `v` with color `c`.
13+
14+
Parameters:
15+
graph (list[list[int]]): The adjacency matrix of the graph.
16+
color (list[int]): The list of colors assigned to each vertex.
17+
v (int): The vertex to check.
18+
c (int): The color to be assigned.
19+
20+
Returns:
21+
bool: True if it's safe to assign color `c` to vertex `v`, otherwise False.
22+
23+
Example:
24+
>>> graph = [[0, 1, 1], [1, 0, 1], [1, 1, 0]]
25+
>>> color = [-1, -1, -1]
26+
>>> is_safe(graph, color, 0, 1)
27+
True
28+
"""
29+
return all(not (graph[v][i] == 1 and color[i] == c) for i in range(len(graph)))
30+
31+
32+
def graph_coloring_util(
33+
graph: list[list[int]], m: int, color: list[int], v: int
34+
) -> bool:
35+
"""
36+
Utility function that uses backtracking to solve the m-coloring problem.
37+
38+
Parameters:
39+
graph (list[list[int]]): The adjacency matrix of the graph.
40+
m (int): The maximum number of colors.
41+
color (list[int]): The list of colors assigned to each vertex.
42+
v (int): The current vertex to be colored.
43+
44+
Returns:
45+
bool: True if all vertices are successfully colored, otherwise False.
46+
47+
Example:
48+
>>> graph = [[0, 1, 1], [1, 0, 1], [1, 1, 0]]
49+
>>> color = [-1, -1, -1]
50+
>>> graph_coloring_util(graph, 3, color, 0)
51+
True
52+
"""
53+
if v == len(graph):
54+
return True
55+
56+
for c in range(1, m + 1):
57+
if is_safe(graph, color, v, c):
58+
color[v] = c
59+
if graph_coloring_util(graph, m, color, v + 1):
60+
return True
61+
color[v] = -1 # Backtrack
62+
63+
return False
64+
65+
66+
def graph_coloring(graph: list[list[int]], m: int) -> bool:
67+
"""
68+
Solves the m-coloring problem using backtracking.
69+
70+
Parameters:
71+
graph (list[list[int]]): The adjacency matrix of the graph.
72+
m (int): The maximum number of colors.
73+
74+
Returns:
75+
bool: True if the graph can be colored with `m` colors, otherwise False.
76+
77+
Example:
78+
>>> graph = [[0, 1, 1], [1, 0, 1], [1, 1, 0]]
79+
>>> graph_coloring(graph, 3)
80+
True
81+
"""
82+
color = [-1] * len(graph)
83+
return graph_coloring_util(graph, m, color, 0)

0 commit comments

Comments
 (0)