0

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?

rnst
  • 1
  • 1
  • What do you mean you can't assign? This assignment works fine, but it's a local variable, so you'd probably have to move it outside the function. Of course, you shouldn't access global variables from a function, so a nested function would be a good approach. – ggorlen Dec 10 '22 at 19:27

0 Answers0