If you can do what you need to do with the paths by getting them one at a time, rather than all at once, then this version of findPaths() runs much faster and uses far less memory. (It runs faster because it uses much less memory.)
For example, on a randomly generated graph that has 10,000 paths, it takes 1.09 seconds instead of 38 seconds for my previous version. In the process, this uses less than 7MB where the previous version used 240MB.
And on a graph that has just over 5 million paths, this still uses just 7MB and completes in 14 1/2 minutes.
I project that the previous version would take 5 1/2 hours to complete, except that it would require 12GB to do so, and I only have 4GB.
It's still the same order of complexity--its essentially the same algorithm--but the simple expedient of avoiding allocating and reallocating zillions of small chunks of ram, mean in the real world it is much faster. Which confirms once again my feelings about big O.
Anyway, if your algorithm can be adapted to operate this way, you might find it useful.
sub _findPaths2 { my( $code, $graph, $start, $end, $path, $seen ) = @_; return $code->( @$path, $end ) if $start eq $end; $seen->{ $start } = 1; for ( grep !$seen->{ $_ }, @{ $graph->{ $start } } ) { _findPaths2( $code, $graph, $_, $end, [ @$path, $start ], { %$ +seen } ), } } sub findPaths2(&@) { _findPaths2( @_, [], {} ); } findPaths2{ print join ' ', @_; } \%graph, $start, $end;
In reply to Re^5: 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: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |