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
- )
11
+ return all (not (graph [node ][k ] == 1 and col [k ] == color )
12
+ for k in range (num_vertices ))
15
13
16
14
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 :
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
@@ -54,17 +48,13 @@ def graph_coloring(graph: list[list[int]], max_colors: int, num_vertices: int) -
54
48
55
49
56
50
if __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 )]
62
54
for _ in range (num_edges ):
63
55
u , v = map (int , input ().split ())
64
56
graph [u ][v ] = 1
65
57
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