I want to implement a backtrack algorithm to find a minimum hamiltonian path, but I ran into a question: why I cannot assign a variable to a value inside the "if" in the code below?
cycle = [0]
start = 0
visited = set()
num_nodes = graph.number_of_nodes()
def backtrack(u, total_distance, shortest_distance):
if len(cycle) == num_nodes and u == 0 and total_distance < shortest_distance:
shortest_distance = total_distance ## CANNOT ASSIGN
return
# for all neighbours
for v in range(num_nodes):
if u != v and v not in visited:
cycle.append(v)
visited.add(v)
total_distance += graph[u][v]['distance']
backtrack(v, total_distance)
cycle.pop()
visited.remove(v)
total_distance -= graph[u][v]['distance']
backtrack(start, 0, float('inf'))
You can easily solve this by saving all minimum distances in a globally defined array, but what I didn't understand is why I cannot do like that: shortest_distance = total_distance
?