|
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 |
6 | 2 |
|
7 | 3 |
|
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: |
9 | 9 | if node == n: |
10 | 10 | return True |
11 | 11 | for c in range(1, m + 1): |
12 | | - if isSafe(node, c, graph, n, col): |
| 12 | + if is_safe(node, c, graph, n, col): |
13 | 13 | col[node] = c |
14 | 14 | if solve(node + 1, col, m, n, graph): |
15 | 15 | return True |
16 | 16 | col[node] = 0 |
17 | 17 | return False |
18 | 18 |
|
19 | 19 |
|
20 | | -def graphColoring(graph, m, n): |
| 20 | +def graph_coloring(graph: List[List[int]], m: int, n: int) -> bool: |
21 | 21 | 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