in reply to find all paths of length n in a graph
This can be modified to allow you to search for multiple depths without having to call the main function multiple times (which would be terribly inefficient!).my $paths_ref = get_paths(\%adjaceny_matrix, $length); sub get_paths { my ($adj, $len) = @_; my @paths; _get_paths_helper(\@paths, $adj, $len, [], {}, [keys %$adj]); return \@paths; } sub _get_paths_helper { my ($p, $am, $len, $curr, $seen, $avail) = @_; for my $v (@$avail) { push @$curr, $v; local $seen->{$v} = 1; if (@$curr == $len) { push @$p, [@$curr] } else { _get_paths_helper($p, $am, $len, $curr, $seen, [grep { !$seen->{ +$_} } @{ $am->{$v} }]); } pop @$curr; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: find all paths of length n in a graph
by Roy Johnson (Monsignor) on Jan 10, 2006 at 20:47 UTC |