Skip to content

Commit 6a5897a

Browse files
authored
Update m_coloring_problem.py
1 parent 4f43023 commit 6a5897a

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

backtracking/m_coloring_problem.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ def is_safe(
1414
True
1515
"""
1616
return all(
17-
not (graph[node][k] == 1 and col[k] == color) for k in range(num_vertices)
17+
not (graph[node][k] == 1 and col[k] == color)
18+
for k in range(num_vertices)
1819
)
1920

2021

@@ -31,7 +32,7 @@ def solve(
3132
>>> solve(0, [0]*3, 3, 3, [[0,1,0],[1,0,1],[0,1,0]])
3233
True
3334
>>> solve(0, [0]*3, 2, 3, [[0,1,0],[1,0,1],[0,1,0]])
34-
False
35+
True
3536
"""
3637
if node == num_vertices:
3738
return True
@@ -44,7 +45,9 @@ def solve(
4445
return False
4546

4647

47-
def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -> bool:
48+
def graph_coloring(
49+
graph: list[list[int]], max_colors: int, num_vertices: int
50+
) -> bool:
4851
"""
4952
Determine if the graph can be colored with at most max_colors.
5053
@@ -66,13 +69,21 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
6669
num_edges = int(input("Enter number of edges: "))
6770
graph = [[0] * num_vertices for _ in range(num_vertices)]
6871

72+
print("Enter the edges (u v):")
6973
for _ in range(num_edges):
70-
u, v = map(int, input().split())
71-
if 0 <= u < num_vertices and 0 <= v < num_vertices:
72-
graph[u][v] = 1
73-
graph[v][u] = 1
74-
else:
75-
raise ValueError("Edge indices out of range")
74+
try:
75+
u, v = map(int, input().split())
76+
if 0 <= u < num_vertices and 0 <= v < num_vertices:
77+
graph[u][v] = 1
78+
graph[v][u] = 1
79+
else:
80+
print(f"Invalid edge: vertices must be between 0 and {num_vertices - 1}.")
81+
except ValueError:
82+
print("Invalid input format. Please enter two integers separated by a space.")
7683

7784
max_colors = int(input("Enter maximum number of colors: "))
78-
print(graph_coloring(graph, max_colors, num_vertices))
85+
86+
if graph_coloring(graph, max_colors, num_vertices):
87+
print("The graph can be colored with the given number of colors.")
88+
else:
89+
print("The graph cannot be colored with the given number of colors.")

0 commit comments

Comments
 (0)