in reply to Re^5: Finding All Paths From a Graph From a Given Source and End Node
in thread Finding All Paths From a Graph From a Given Source and End Node
my %graph2 = ( 'read145404_1' => [ 'read231054_2', 'read250449_2' ], 'read250449_2' => [ 'read359463_1', 'read691358_1', 'read937013_1' ], 'read231054_2' => [ 'read691358_1', 'read359463_1', 'read937013_1' ] ); my $routes = find_paths('read145404_1', 'read691358_1', \%graph2); sub find_paths { my ($beg, $end, $graph) = @_; my $n; my %node_to_int = map {$_ => $n++} keys %graph; my (@work, @solution); for (@{$graph->{$beg}}) { if ($_ eq $end) { push @solution, "$beg->$end"; next; } my $seen = ''; vec($seen, $node_to_int{$_}, 1) = 1; vec($seen, $node_to_int{$beg}, 1) = 1; push @work, ["$beg->$_", $_, $seen]; } while (@work) { my $item = pop @work; my ($path, $curr, $seen) = @$item; for my $node (@{$graph->{$curr}}) { my $bit = $node_to_int{$node}; next if vec($seen, $bit, 1); if ($node eq $end) { push @solution, "$path $end"; next; } my $new_seen = $seen; vec($new_seen, $bit, 1) = 1; push @work, ["$path->$node", $node, $new_seen]; } } # Return print Dumper \@solution; return \@solution; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^7: Finding All Paths From a Graph From a Given Source and End Node
by Limbic~Region (Chancellor) on Nov 01, 2010 at 14:56 UTC |