我有一个在这里运行良好的代码:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %graph =(
F => ['B','C','E'],
A => ['B','C'],
D => ['B'],
C => ['A','E','F'],
E => ['C','F'],
B => ['A','E','F']
);
sub findPaths {
my( $seen, $start, $end ) = @_;
return [[$end]] if $start eq $end;
$seen->{ $start } = 1;
my @paths;
for my $node ( @{ $graph{ $start } } ) {
my %seen = %{$seen};
next if exists $seen{ $node };
push @paths, [ $start, @$_ ] for @{ findPaths( \%seen, $node, $end ) };
}
return \@paths;
}
my $start = "B";
my $end = "E";
print "@$_\n" for @{ findPaths( {}, $start, $end ) };
我想要做的是生成一个更通用的子程序,以便它只\%graph, $start,$end
作为输入并返回最终数组。
我试图这样做,但它没有编译。
sub findPathsAll {
my ($graph,$start,$end) = @_;
my $findPaths_sub;
$findPaths_sub {
my( $seen) = @_;
return [[$end]] if $start eq $end;
$seen->{ $start } = 1;
my @paths;
for my $node ( @{ $graph{ $start } } ) {
my %seen = %{$seen};
next if exists $seen{ $node };
push @paths, [ $start, @$_ ] for @{ &$findPaths_sub( \%seen, $node, $end ) };
}
return \@paths;
}
my @all;
push @all,@$_ for @{ &$findPaths_sub( {}, $start, $end ) };
return @all;
}
正确的方法是什么?