in reply to Finding All Paths From a Graph From a Given Source and End Node
use strict; use warnings; use Data::Dumper; $|=1; my $start="B"; my $stop="E"; my %graph =( 'F' => ['B','C','E'], 'A' => ['B','C'], 'D' => ['B'], 'C' => ['A','E','F'], 'E' => ['C','F'], 'B' => ['A','E','F'] ); track($start); sub track { my @path=@_; my $last=$path[-1]; for my $next (@{$graph{$last}}) { next if $next ~~ @path; # next if grep {$_ eq $next } @path; if ($next eq $stop){ print join ("->",@path,$stop),"\n"; } else { track(@path,$next); } } }
prints
B->A->C->E B->A->C->F->E B->E B->F->C->E B->F->E
for large graphs you should consider using a hash instead of passing an array to speed up the test.
Cheers Rolf
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Finding All Paths From a Graph From a Given Source and End Node
by LanX (Saint) on Oct 28, 2010 at 23:25 UTC | |
|
Re^2: Finding All Paths From a Graph From a Given Source and End Node
by Anonymous Monk on Feb 21, 2014 at 10:48 UTC |