ベルマン−フォード・アルゴリズムは、ダイクストラ法にさらに辺の重みが負の場合も含めて最短経路を求めることができます。入出力などはダイクストラ法の場合を参照して下さい。 コーディングは Ruby で行いました。返り値は配列 [shortest, pred] で、pred を見ると最短経路がわかります。 bellman_ford.rb def bellman_ford(g, s) h = g.map {|x| [x[0], x[1].keys]}.to_h shortest = Hash.new(Float::INFINITY) pred = {} shortest[s] = 0 (h.size - 1).times do h.each do |k, v| v.each do |x| if (a = shortest[k] + g[k][x]) < shortest[x] shortest[x
![ベルマン−フォード・アルゴリズム(Ruby) - Camera Obscura](https://cdn-ak-scissors.b.st-hatena.com/image/square/d82082015b134c699455b5c7ea21d2ccc01da0ed/height=288;version=1;width=512/http%3A%2F%2Fimg.f.hatena.ne.jp%2Fimages%2Ffotolife%2Fo%2Fobelisk2%2F20170808%2F20170808161948.png)