In that case, try this:
#! perl -slw use strict; sub _pathsFrom { my( $code, $graph, $start, $path, $seen ) = @_; return $code->( @$path, $start ) unless exists $graph->{ $start }; for my $next ( @{ $graph->{ $start } } ) { if( exists $seen->{ "$start-$next" } ) { return $code->( @$path, $start ); } else { _pathsFrom( $code, $graph, $next, [ @$path, $start ], { %$seen, "$start-$next", undef } ); } } } sub pathsFrom(&@) { _pathsFrom( @_, [], {} ) } my %graph = ( a => [ 'b' ], b => [ 'c' ], c => [ 'd', 'j' ], d => [ 'e', 'g' ], g => [ 'h' ], h => [ 'c' ], j => [ 'k' ], ); pathsFrom{ print join '->', @_; } \%graph, 'a'; __END__ c:\test>904729-2 a->b->c->d->e a->b->c->d->g->h->c->j->k a->b->c->j->k
This version is the identical algorithm but somewhat more efficient:
use enum qw[ CODE GRAPH START PATH SEEN ]; sub _pathsFrom2 { return $_[CODE]->( @{ $_[PATH] }, $_[START] ) unless exists $_[GRAPH]->{ $_[START] }; for ( @{ $_[GRAPH]->{ $_[START] } } ) { if( exists $_[SEEN]->{ $_[START] . "-$_" } ) { return $_[CODE]->( @{ $_[PATH] }, $_[START] ); } else { _pathsFrom2( @_[ CODE, GRAPH ], $_, [ @{ $_[PATH] }, $_[START] ], { %{ $_[SEEN] }, $_[START] . "-$_", undef } ); } } } sub pathsFrom(&@) { _pathsFrom2( @_, [], {} ) }
BTW: If you have a dataset that forms a decent sized test I'd like to get a copy as I've found generating legal directed graphs quite difficult.
In reply to Re^17: Finding All Paths From a Graph From a Given Source and End Node
by BrowserUk
in thread Finding All Paths From a Graph From a Given Source and End Node
by neversaint
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |