# # Takes a graph and a root element as arguments. # The graph is a doubled keyed hash, with # $graph{a}{b} = x; # indicating there's an edge from a to b with distance x. # # If the graph is supposed to be bidirectional, make sure that # for all a, b, $graph{a}{b} = $graph{b}{a}. # sub dijkstra { my $graph = shift; my $root = shift; my %dist; # Distance to root element. my @todo = [$root, 0]; { my ($to, $distance) = @{shift @todo}; unless (exists $dist{$to}) { # # Have not been here # $dist{$to} = $distance; @todo = sort {$$a[1] <=> $$b[1]} @todo, map {[$_, $distance + $$graph{$to}{$_}]} keys %{$$graph{$to}}; } } return \%dist; }