#!/usr/bin/perl use constant LAST => -1; use constant PATH => 0; use constant SEEN => 1; use strict; use warnings; my %graph = ( F => [qw/B C E/], A => [qw/B C/], D => [qw/B/], C => [qw/A E F/], E => [qw/C F/], B => [qw/A E F/] ); my $routes = find_paths('B', 'E', \%graph); print "@$_\n" for @$routes; sub find_paths { my ($beg, $end, $graph) = @_; my @solution; my @work; for (@{$graph->{$beg}}) { push @solution, [$beg, $end] if $_ eq $end; push @work, [[$beg, $_], {$beg => undef, $_ => undef}]; } while (@work) { my $item = pop @work; my ($path, $seen) = @{$item}[PATH, SEEN]; for my $node (@{$graph->{$path->[LAST]}}) { next if exists $seen->{$node}; my @new_path = (@$path, $node); if ($node eq $end) { push @solution, \@new_path; next; } my %new_seen = (%$seen, $node => undef); push @work, [\@new_path, \%new_seen]; } } return \@solution; }