CSCE 411 Lecture 21

From Notes
Jump to navigation Jump to search
Lecture Slides

« previous | Monday, October 15, 2012 | next »


Bellman-Ford Algorithm

Similar to Dijkstra's Algorithm, but can handle negative edge weights (and can even detect negative weight cycles if they exist).

Basic Idea:

  • Consider each edge and see if offers a cheaper path from (compare to .
  • Repeat process times to ensure that accurate information propagates from , no matter what order the edges are considered.
def bellman_ford graph, source
  # initialization
  graph.each_vertex {|v| v.distance = Float::INFINITY; v.parent = nil }
  source.parent = source
  source.distance = 0

  # main body
  1.upto(graph.vertices.size - 1) do
    edge_relaxed = false

    graph.each_edge do |edge|
      if edge.start.distance + edge.weight < edge.end.distance
        edge.end.distance = edge.start.distance + edge.weight
        edge.end.parent = edge.start
        edge_relaxed = true
      end
    end

    # optimization
    break unless edge_relaxed
  end

  # check for negative weight cycles
  graph.each_edge do |edge|
    if edge.start.distance + edge.weight < edge.end.distance
      throw "Negative weight cycle detected!"
    end
  end
end

Correctness

Assume no negative-weight cycles

Lemma: is never an underestimate of the actual shortest path distance from to .

Lemma: If there is a shortest path containing at most edges, then after iteration of the outer loop, is at most the shortest path distance from to .