1- def is_safe (
2- node : int , color : int , graph : list [list [int ]], num_vertices : int , col : list [int ]
3- ) -> bool :
1+ def is_safe (node : int , color : int , graph : list [list [int ]], num_vertices : int ,
2+ col : list [int ]) -> bool :
43 """
54 Check if it is safe to assign a color to a node.
65
@@ -9,18 +8,12 @@ def is_safe(
98 >>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
109 True
1110 """
12- return all (
13- not (graph [node ][k ] == 1 and col [k ] == color ) for k in range (num_vertices )
14- )
11+ return all (not (graph [node ][k ] == 1 and col [k ] == color )
12+ for k in range (num_vertices ))
1513
1614
17- def solve (
18- node : int ,
19- col : list [int ],
20- max_colors : int ,
21- num_vertices : int ,
22- graph : list [list [int ]],
23- ) -> bool :
15+ def solve (node : int , col : list [int ], max_colors : int , num_vertices : int ,
16+ graph : list [list [int ]]) -> bool :
2417 """
2518 Recursively try to color the graph using at most max_colors.
2619
@@ -40,7 +33,8 @@ def solve(
4033 return False
4134
4235
43- def graph_coloring (graph : list [list [int ]], max_colors : int , num_vertices : int ) -> bool :
36+ def graph_coloring (graph : list [list [int ]], max_colors : int ,
37+ num_vertices : int ) -> bool :
4438 """
4539 Determine if the graph can be colored with at most max_colors.
4640
@@ -54,17 +48,13 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
5448
5549
5650if __name__ == "__main__" :
57- print ("Graph Coloring Problem" )
58- num_vertices = int (input ("Enter number of vertices: " ))
59- num_edges = int (input ("Enter number of edges: " ))
60- print ("Enter each edge as 'u v' (0-based indexing):" )
61- graph = [[0 ] * num_vertices for _ in range (num_vertices )]
51+ num_vertices = int (input ())
52+ num_edges = int (input ())
53+ graph = [[0 ]* num_vertices for _ in range (num_vertices )]
6254 for _ in range (num_edges ):
6355 u , v = map (int , input ().split ())
6456 graph [u ][v ] = 1
6557 graph [v ][u ] = 1
66- max_colors = int (input ("Enter maximum number of colors: " ))
67- if graph_coloring (graph , max_colors , num_vertices ):
68- print (f"The graph can be colored with { max_colors } colors." )
69- else :
70- print (f"The graph cannot be colored with { max_colors } colors." )
58+ max_colors = int (input ())
59+ col = [0 ]* num_vertices
60+ print (solve (0 , col , max_colors , num_vertices , graph ))
0 commit comments