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- )
15-
16-
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 :
11+ return all (not (graph [node ][k ] == 1 and col [k ] == color )
12+ for k in range (num_vertices ))
13+
14+
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
@@ -51,3 +45,20 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
5145 """
5246 col = [0 ] * num_vertices
5347 return solve (0 , col , max_colors , num_vertices , graph )
48+
49+
50+ if __name__ == "__main__" :
51+ print ("Graph Coloring Problem" )
52+ num_vertices = int (input ("Enter number of vertices: " ))
53+ num_edges = int (input ("Enter number of edges: " ))
54+ print ("Enter each edge as 'u v' (0-based indexing):" )
55+ graph = [[0 ]* num_vertices for _ in range (num_vertices )]
56+ for _ in range (num_edges ):
57+ u , v = map (int , input ().split ())
58+ graph [u ][v ] = 1
59+ graph [v ][u ] = 1
60+ max_colors = int (input ("Enter maximum number of colors: " ))
61+ if graph_coloring (graph , max_colors , num_vertices ):
62+ print (f"The graph can be colored with { max_colors } colors." )
63+ else :
64+ print (f"The graph cannot be colored with { max_colors } colors." )
0 commit comments