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 :
4
3
"""
5
4
Check if it is safe to assign a color to a node.
6
5
@@ -9,18 +8,12 @@ def is_safe(
9
8
>>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
10
9
True
11
10
"""
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 :
24
17
"""
25
18
Recursively try to color the graph using at most max_colors.
26
19
@@ -40,7 +33,8 @@ def solve(
40
33
return False
41
34
42
35
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 :
44
38
"""
45
39
Determine if the graph can be colored with at most max_colors.
46
40
@@ -51,3 +45,20 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
51
45
"""
52
46
col = [0 ] * num_vertices
53
47
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