in reply to Re^3: 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

Here is my code as it is (your subs removed):
#!/usr/bin/perl use warnings; use strict; use Benchmark qw/cmpthese/; my %graph =( 'F' => ['B','C','E'], 'A' => ['B','C'], 'D' => ['B'], 'C' => ['A','E','F'], 'E' => ['C','F'], 'B' => ['A','E','F'], x => ['y','z'], y => ['u','v'], z => ['w','x'], u => [], v => [], w => [], ); sub try_path_depth { my ($start,$end,@sofar) = @_; if ($start eq $end) { return 1; } push @sofar,$start; foreach my $node(@{ $graph{$start} }){ unless (grep $_ eq $node,@sofar){ if(try_path_depth($node,$end,@sofar)){ print "@sofar $end\n"; } } } } # try_path_depth sub path_depth { my ($start,$end) = @_; print "$start => $end\n"; try_path_depth($start,$end); } # path_depth sub uniq { my %uniq; @uniq{@_} = (); return keys %uniq; } #uniq sub try_path_breadth { my($start,$end) = @_; my @from = ($start); my %path = ($start => [$start]); my $change = 1; while($change){ undef $change; my %newpath; my @to = uniq(map @{ $graph{$_} },@from); foreach my $from (@from) { foreach my $to (@{ $graph{$from} }){ for my $path (grep { $_ !~ /$to/ and $change = 1} @{$path{$fro +m}}){ unless(grep $path.$to eq $_,@{$newpath{$to}}){ push @{ $newpath{$to} },$path.$to; $change = 1; } } } } %path = %newpath; print "$_\n" foreach @{ $path{$end} }; @from = @to; } } # try_path_breadth sub path_breadth { my ($start,$end) = @_; print "$start => $end\n"; try_path_breadth($start,$end); } # path_breadth sub find_paths { ... } sub find_paths_sc { ... } sub node_to_int { ... } sub update_completed_paths { ... } sub path_completed { ... } cmpthese(0,{depth => sub{ path_depth 'B','E'; path_depth 'B','D'; path_depth 'z','v';}, breadth => sub{ path_breadth 'B','E'; path_breadth 'B','D'; path_breadth 'z','v';}, limbic => sub{ print @{find_paths 'B','E',\%graph}, @{find_paths 'B','D',\%graph}, @{find_paths 'z','v',\%graph};}, limbic_sc => sub{ print @{find_paths_sc 'B','E',\%graph}, @{find_paths_sc 'B','D',\%graph}, @{find_paths_sc 'z','v',\%graph};}, });
  • Comment on Re^4: Finding All Paths From a Graph From a Given Source and End Node
  • Download Code