Pseudo-Code Base Case: 1. Check if coloring is complete 1.1 If complete return True (meaning that we successfully colored the graph) Recursive Step: 2. Iterates over each color: Check if the current coloring is valid: 2.1. Color given vertex
(
graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int
)
| 34 | |
| 35 | |
| 36 | def util_color( |
| 37 | graph: list[list[int]], max_colors: int, colored_vertices: list[int], index: int |
| 38 | ) -> bool: |
| 39 | """ |
| 40 | Pseudo-Code |
| 41 | |
| 42 | Base Case: |
| 43 | 1. Check if coloring is complete |
| 44 | 1.1 If complete return True (meaning that we successfully colored the graph) |
| 45 | |
| 46 | Recursive Step: |
| 47 | 2. Iterates over each color: |
| 48 | Check if the current coloring is valid: |
| 49 | 2.1. Color given vertex |
| 50 | 2.2. Do recursive call, check if this coloring leads to a solution |
| 51 | 2.4. if current coloring leads to a solution return |
| 52 | 2.5. Uncolor given vertex |
| 53 | |
| 54 | >>> graph = [[0, 1, 0, 0, 0], |
| 55 | ... [1, 0, 1, 0, 1], |
| 56 | ... [0, 1, 0, 1, 0], |
| 57 | ... [0, 1, 1, 0, 0], |
| 58 | ... [0, 1, 0, 0, 0]] |
| 59 | >>> max_colors = 3 |
| 60 | >>> colored_vertices = [0, 1, 0, 0, 0] |
| 61 | >>> index = 3 |
| 62 | |
| 63 | >>> util_color(graph, max_colors, colored_vertices, index) |
| 64 | True |
| 65 | |
| 66 | >>> max_colors = 2 |
| 67 | >>> util_color(graph, max_colors, colored_vertices, index) |
| 68 | False |
| 69 | """ |
| 70 | |
| 71 | # Base Case |
| 72 | if index == len(graph): |
| 73 | return True |
| 74 | |
| 75 | # Recursive Step |
| 76 | for i in range(max_colors): |
| 77 | if valid_coloring(graph[index], colored_vertices, i): |
| 78 | # Color current vertex |
| 79 | colored_vertices[index] = i |
| 80 | # Validate coloring |
| 81 | if util_color(graph, max_colors, colored_vertices, index + 1): |
| 82 | return True |
| 83 | # Backtrack |
| 84 | colored_vertices[index] = -1 |
| 85 | return False |
| 86 | |
| 87 | |
| 88 | def color(graph: list[list[int]], max_colors: int) -> list[int]: |
no test coverage detected