Skip to content

Commit 96ba61e

Browse files
authored
Update m_coloring_problem.py
1 parent a729c20 commit 96ba61e

File tree

1 file changed

+6
-11
lines changed

1 file changed

+6
-11
lines changed

backtracking/m_coloring_problem.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
def is_safe(node: int, color: int, graph: list[list[int]], num_vertices: int,
2-
col: list[int]) -> bool:
1+
def is_safe(node: int, color: int, graph: list[list[int]], num_vertices: int, col: list[int]) -> bool:
32
"""
43
Check if it is safe to assign a color to a node.
54
@@ -8,12 +7,10 @@ def is_safe(node: int, color: int, graph: list[list[int]], num_vertices: int,
87
>>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
98
True
109
"""
11-
return all(not (graph[node][k] == 1 and col[k] == color)
12-
for k in range(num_vertices))
10+
return all(not (graph[node][k] == 1 and col[k] == color) for k in range(num_vertices))
1311

1412

15-
def solve(node: int, col: list[int], max_colors: int, num_vertices: int,
16-
graph: list[list[int]]) -> bool:
13+
def solve(node: int, col: list[int], max_colors: int, num_vertices: int, graph: list[list[int]]) -> bool:
1714
"""
1815
Recursively try to color the graph using at most max_colors.
1916
@@ -33,8 +30,7 @@ def solve(node: int, col: list[int], max_colors: int, num_vertices: int,
3330
return False
3431

3532

36-
def graph_coloring(graph: list[list[int]], max_colors: int,
37-
num_vertices: int) -> bool:
33+
def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -> bool:
3834
"""
3935
Determine if the graph can be colored with at most max_colors.
4036
@@ -50,7 +46,7 @@ def graph_coloring(graph: list[list[int]], max_colors: int,
5046
if __name__ == "__main__":
5147
num_vertices = int(input())
5248
num_edges = int(input())
53-
graph = [[0]*num_vertices for _ in range(num_vertices)]
49+
graph = [[0] * num_vertices for _ in range(num_vertices)]
5450
for _ in range(num_edges):
5551
u, v = map(int, input().split())
5652
if 0 <= u < num_vertices and 0 <= v < num_vertices:
@@ -59,5 +55,4 @@ def graph_coloring(graph: list[list[int]], max_colors: int,
5955
else:
6056
raise ValueError("Edge indices out of range")
6157
max_colors = int(input())
62-
col = [0]*num_vertices
63-
print(solve(0, col, max_colors, num_vertices, graph))
58+
print(graph_coloring(graph, max_colors, num_vertices))

0 commit comments

Comments
 (0)