Skip to content

Commit 5dba8a1

Browse files
authored
Update m_coloring_problem.py
1 parent 80cfe21 commit 5dba8a1

File tree

1 file changed

+9
-26
lines changed

1 file changed

+9
-26
lines changed

backtracking/m_coloring_problem.py

Lines changed: 9 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,22 @@
1-
def isSafe(node, color, graph, n, col):
2-
for k in range(n):
3-
if graph[node][k] == 1 and col[k] == color:
4-
return False
5-
return True
1+
from typing import List
62

73

8-
def solve(node, col, m, n, graph):
4+
def is_safe(node: int, color: int, graph: List[List[int]], n: int, col: List[int]) -> bool:
5+
return all(not (graph[node][k] == 1 and col[k] == color) for k in range(n))
6+
7+
8+
def solve(node: int, col: List[int], m: int, n: int, graph: List[List[int]]) -> bool:
99
if node == n:
1010
return True
1111
for c in range(1, m + 1):
12-
if isSafe(node, c, graph, n, col):
12+
if is_safe(node, c, graph, n, col):
1313
col[node] = c
1414
if solve(node + 1, col, m, n, graph):
1515
return True
1616
col[node] = 0
1717
return False
1818

1919

20-
def graphColoring(graph, m, n):
20+
def graph_coloring(graph: List[List[int]], m: int, n: int) -> bool:
2121
col = [0] * n
22-
if solve(0, col, m, n, graph):
23-
return True
24-
return False
25-
26-
27-
if __name__ == "__main__":
28-
V = int(input())
29-
E = int(input())
30-
graph = [[0 for _ in range(V)] for _ in range(V)]
31-
for _ in range(E):
32-
u, v = map(int, input().split())
33-
graph[u][v] = 1
34-
graph[v][u] = 1
35-
m = int(input())
36-
if graphColoring(graph, m, V):
37-
print("True")
38-
else:
39-
print("False")
22+
return solve(0, col, m, n, graph)

0 commit comments

Comments
 (0)