#!/usr/bin/perl 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 (@work, @solution); for (@{$graph->{$beg}}) { if ($_ eq $end) { push @solution, "$beg->$end"; next; } my $seen = ''; vec($seen, node_to_int($_), 1) = 1; vec($seen, node_to_int($beg), 1) = 1; push @work, ["$beg->$_", $_, $seen]; } while (@work) { my $item = pop @work; my ($path, $curr, $seen) = @$item; for my $node (@{$graph->{$curr}}) { my $bit = node_to_int($node); next if vec($seen, $bit, 1); if ($node eq $end) { push @solution, "$path->$end"; next; } my $new_seen = $seen; vec($new_seen, $bit, 1) = 1; push @work, ["$path->$node", $node, $new_seen]; } } return \@solution; } sub node_to_int { my ($node) = @_; return ord($node) - 65; }