22
33
44def is_safe (node : int , color : int , graph : List [List [int ]], n : int , col : List [int ]) -> bool :
5+ """
6+ Check if it is safe to assign a color to a node.
7+
8+ >>> is_safe(0, 1, [[0,1],[1,0]], 2, [0,1])
9+ False
10+ >>> is_safe(0, 2, [[0,1],[1,0]], 2, [0,1])
11+ True
12+ """
513 return all (not (graph [node ][k ] == 1 and col [k ] == color ) for k in range (n ))
614
715
816def solve (node : int , col : List [int ], m : int , n : int , graph : List [List [int ]]) -> bool :
17+ """
18+ Recursively try to color the graph using at most m colors.
19+
20+ >>> solve(0, [0]*3, 3, 3, [[0,1,0],[1,0,1],[0,1,0]])
21+ True
22+ >>> solve(0, [0]*3, 2, 3, [[0,1,0],[1,0,1],[0,1,0]])
23+ False
24+ """
925 if node == n :
1026 return True
1127 for c in range (1 , m + 1 ):
@@ -18,5 +34,13 @@ def solve(node: int, col: List[int], m: int, n: int, graph: List[List[int]]) ->
1834
1935
2036def graph_coloring (graph : List [List [int ]], m : int , n : int ) -> bool :
37+ """
38+ Determine if the graph can be colored with at most m colors.
39+
40+ >>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 3, 3)
41+ True
42+ >>> graph_coloring([[0,1,1],[1,0,1],[1,1,0]], 2, 3)
43+ False
44+ """
2145 col = [0 ] * n
2246 return solve (0 , col , m , n , graph )
0 commit comments