MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / hamilton_cycle

Function hamilton_cycle

backtracking/hamiltonian_cycle.py:110–176  ·  view source on GitHub ↗

r""" Wrapper function to call subroutine called util_hamilton_cycle, which will either return array of vertices indicating hamiltonian cycle or an empty list indicating that hamiltonian cycle was not found. Case 1: Following graph consists of 5 edges. If we look closely, we c

(graph: list[list[int]], start_index: int = 0)

Source from the content-addressed store, hash-verified

108
109
110def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]:
111 r"""
112 Wrapper function to call subroutine called util_hamilton_cycle,
113 which will either return array of vertices indicating hamiltonian cycle
114 or an empty list indicating that hamiltonian cycle was not found.
115 Case 1:
116 Following graph consists of 5 edges.
117 If we look closely, we can see that there are multiple Hamiltonian cycles.
118 For example one result is when we iterate like:
119 (0)->(1)->(2)->(4)->(3)->(0)
120
121 (0)---(1)---(2)
122 | / \ |
123 | / \ |
124 | / \ |
125 |/ \|
126 (3)---------(4)
127 >>> graph = [[0, 1, 0, 1, 0],
128 ... [1, 0, 1, 1, 1],
129 ... [0, 1, 0, 0, 1],
130 ... [1, 1, 0, 0, 1],
131 ... [0, 1, 1, 1, 0]]
132 >>> hamilton_cycle(graph)
133 [0, 1, 2, 4, 3, 0]
134
135 Case 2:
136 Same Graph as it was in Case 1, changed starting index from default to 3
137
138 (0)---(1)---(2)
139 | / \ |
140 | / \ |
141 | / \ |
142 |/ \|
143 (3)---------(4)
144 >>> graph = [[0, 1, 0, 1, 0],
145 ... [1, 0, 1, 1, 1],
146 ... [0, 1, 0, 0, 1],
147 ... [1, 1, 0, 0, 1],
148 ... [0, 1, 1, 1, 0]]
149 >>> hamilton_cycle(graph, 3)
150 [3, 0, 1, 2, 4, 3]
151
152 Case 3:
153 Following Graph is exactly what it was before, but edge 3-4 is removed.
154 Result is that there is no Hamiltonian Cycle anymore.
155
156 (0)---(1)---(2)
157 | / \ |
158 | / \ |
159 | / \ |
160 |/ \|
161 (3) (4)
162 >>> graph = [[0, 1, 0, 1, 0],
163 ... [1, 0, 1, 1, 1],
164 ... [0, 1, 0, 0, 1],
165 ... [1, 1, 0, 0, 0],
166 ... [0, 1, 1, 0, 0]]
167 >>> hamilton_cycle(graph,4)

Callers

nothing calls this directly

Calls 1

util_hamilton_cycleFunction · 0.85

Tested by

no test coverage detected