The way the Bellman Ford algorithm has been explained to me is that it goes through n-1 (with n being the number of nodes) iterations, updating the distance between nodes on each iteration. All graphical examples show the nodes initialized to infinity, and the ones closest to the source node being updated on the first iteration, but the rest remaining at infinity until an iteration occurs that reaches them.
However, looking at code for the algorithm, such as that provided here, I’m finding it hard to understand why all of the nodes that are more steps away than the number of iterations are not updated with the algorithm. For instance, if I’m on my second iteration and I have a node d that is only reachable through the path a-b-c-d, the examples I’ve read seem to indicate that d will not be updated until the 4th iteration.
But the main relaxation function of the code:
def relax(node, neighbour, graph, d, p):
# If the distance between the node and the neighbour is lower than the one I have now
if d[neighbour] > d[node] + graph[node][neighbour]:
# Record this lower distance
d[neighbour] = d[node] + graph[node][neighbour]
p[neighbour] = node
updates based on information giving the weight and distance from the source of the predecessor node. If the algorithm iterates over each node in every iteration, what’s to stop d from being properly updated in the FIRST iteration? For instance, if the algorithm iterated over the nodes in order a-b-c-d, I don’t see why the algorithm wouldn’t store the distance information for node b, move on to node c, store distance information for that, and finally reach d with enough information to calculate the shortest path IN THE FIRST ITERATION.
I hope that made some kind of sense.
It could happen – but it is not guaranteed. You can only guarantee that you have shortest path of length up to
kat the k’th iteration, not earlier.The visualizations you saw are just there for explaining the concept of the algorithm, and it is much cleaner and simpler to understand using a transactional memory model.
Think how hard it was for you to understand the algorithm using the visualization if a node of distance 10 would change in the first iteration…
Regarding the question in comment:
Yes, if there are no changes in iteration
k– iterationk+1wont be able to change anything as well, everything is minimal, and so does fork+2, …