Pseudo-Code Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current
(graph: list[list[int]], path: list[int], curr_ind: int)
| 47 | |
| 48 | |
| 49 | def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: |
| 50 | """ |
| 51 | Pseudo-Code |
| 52 | Base Case: |
| 53 | 1. Check if we visited all of vertices |
| 54 | 1.1 If last visited vertex has path to starting vertex return True either |
| 55 | return False |
| 56 | Recursive Step: |
| 57 | 2. Iterate over each vertex |
| 58 | Check if next vertex is valid for transiting from current vertex |
| 59 | 2.1 Remember next vertex as next transition |
| 60 | 2.2 Do recursive call and check if going to this vertex solves problem |
| 61 | 2.3 If next vertex leads to solution return True |
| 62 | 2.4 Else backtrack, delete remembered vertex |
| 63 | |
| 64 | Case 1: Use exact graph as in main function, with initialized values |
| 65 | >>> graph = [[0, 1, 0, 1, 0], |
| 66 | ... [1, 0, 1, 1, 1], |
| 67 | ... [0, 1, 0, 0, 1], |
| 68 | ... [1, 1, 0, 0, 1], |
| 69 | ... [0, 1, 1, 1, 0]] |
| 70 | >>> path = [0, -1, -1, -1, -1, 0] |
| 71 | >>> curr_ind = 1 |
| 72 | >>> util_hamilton_cycle(graph, path, curr_ind) |
| 73 | True |
| 74 | >>> path |
| 75 | [0, 1, 2, 4, 3, 0] |
| 76 | |
| 77 | Case 2: Use exact graph as in previous case, but in the properties taken from |
| 78 | middle of calculation |
| 79 | >>> graph = [[0, 1, 0, 1, 0], |
| 80 | ... [1, 0, 1, 1, 1], |
| 81 | ... [0, 1, 0, 0, 1], |
| 82 | ... [1, 1, 0, 0, 1], |
| 83 | ... [0, 1, 1, 1, 0]] |
| 84 | >>> path = [0, 1, 2, -1, -1, 0] |
| 85 | >>> curr_ind = 3 |
| 86 | >>> util_hamilton_cycle(graph, path, curr_ind) |
| 87 | True |
| 88 | >>> path |
| 89 | [0, 1, 2, 4, 3, 0] |
| 90 | """ |
| 91 | |
| 92 | # Base Case |
| 93 | if curr_ind == len(graph): |
| 94 | # return whether path exists between current and starting vertices |
| 95 | return graph[path[curr_ind - 1]][path[0]] == 1 |
| 96 | |
| 97 | # Recursive Step |
| 98 | for next_ver in range(len(graph)): |
| 99 | if valid_connection(graph, next_ver, curr_ind, path): |
| 100 | # Insert current vertex into path as next transition |
| 101 | path[curr_ind] = next_ver |
| 102 | # Validate created path |
| 103 | if util_hamilton_cycle(graph, path, curr_ind + 1): |
| 104 | return True |
| 105 | # Backtrack |
| 106 | path[curr_ind] = -1 |
no test coverage detected