Rubyでdijkstra法
Rubyでダイクストラ法を使って始点からの最短経路を求めることができるかもしれないコード
nodes = ["A", "B", "C", "D", "E"] connections = [ # [node1, node2, cost(1->2), cost(2->1)] ["A", "B", 6, 9], ["A", "C", 3, 2], ["B", "C", 2, 3], ["B", "D", 4, 1], ["C", "E", 3, 8], ["B", "E", 3, 2], ] require 'pp' def dijkstra(nodes, connections, start) inf = 100000 d = {} cost = {} used = {} prev = {} nodes.each{|n| d[n] = {} nodes.each{|m| d[n][m] = inf } cost[n] = inf used[n] = 0 } connections.each{|c| d[c[1]][c[0]] = c[2] ? c[2] : 1 d[c[0]][c[1]] = c[3] ? c[3] : (c[2]?c[2]:1) } cost[start] = 0 while true min_cost = inf nodes.each{|node| if used[node] == 0 && min_cost > cost[node] min_cost = cost[node] end } break if min_cost == inf nodes.each{|src| next if min_cost != cost[src] nodes.each{|dst| next if cost[dst] <= d[dst][src] + cost[src] cost[dst] = d[dst][src] + cost[src] prev[dst] = src } used[src] = 1 } end routes = {} nodes.each{|dst| route = [] node = dst while node != nil && node != start route << node node = prev[node] end routes[dst] = route.reverse } return routes end routes = {} nodes.each{|st| rs = dijkstra(nodes, connections, st) rs.each{|d,r| k = st+'-'+d routes[k] = [] m = st r.each{|n| routes[k] << m+'-'+n m = n } } } pp routes
{"B-A"=>["B-C", "C-A"], "A-B"=>["A-B"], "C-A"=>["C-A"], "B-B"=>[], "A-C"=>["A-C"], "D-A"=>["D-B", "B-C", "C-A"], "C-B"=>["C-B"], "B-C"=>["B-C"], "A-D"=>["A-B", "B-D"], "E-A"=>["E-B", "B-C", "C-A"], "D-B"=>["D-B"], "C-C"=>[], "B-D"=>["B-D"], "A-E"=>["A-C", "C-E"], "E-B"=>["E-B"], "D-C"=>["D-B", "B-C"], "C-D"=>["C-B", "B-D"], "B-E"=>["B-E"], "E-C"=>["E-B", "B-C"], "D-D"=>[], "C-E"=>["C-E"], "E-D"=>["E-B", "B-D"], "D-E"=>["D-B", "B-E"], "E-E"=>[], "A-A"=>[]}