@@ -14,7 +14,8 @@ def is_safe(
14
14
True
15
15
"""
16
16
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 )
18
19
)
19
20
20
21
@@ -31,7 +32,7 @@ def solve(
31
32
>>> solve(0, [0]*3, 3, 3, [[0,1,0],[1,0,1],[0,1,0]])
32
33
True
33
34
>>> solve(0, [0]*3, 2, 3, [[0,1,0],[1,0,1],[0,1,0]])
34
- False
35
+ True
35
36
"""
36
37
if node == num_vertices :
37
38
return True
@@ -44,7 +45,9 @@ def solve(
44
45
return False
45
46
46
47
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 :
48
51
"""
49
52
Determine if the graph can be colored with at most max_colors.
50
53
@@ -66,13 +69,21 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
66
69
num_edges = int (input ("Enter number of edges: " ))
67
70
graph = [[0 ] * num_vertices for _ in range (num_vertices )]
68
71
72
+ print ("Enter the edges (u v):" )
69
73
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." )
76
83
77
84
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