neversaint,
The problem was that the %node_to_int lookup assumed all possible nodes would also be keys in graph. One way to fix it would be to have nodes that don't connect anywhere as node => [] (empty array ref). I chose to provide a solution below that doesn't require the user to type more than is necessary when building the graph.
#!/usr/bin/perl use strict; use warnings; my %graph = ( read145404_1 => [qw/read231054_2 read250449_2/], read231054_2 => [qw/read359463_1 read691358_1 read937013_1/], read250449_2 => [qw/read359463_1 read691358_1 read937013_1/], ); my %node_to_int = convert_node_to_int(\%graph); my $routes = find_paths('read145404_1', 'read691358_1', \%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 convert_node_to_int { my ($graph) = @_; my ($n, %lookup); for my $node (keys %$graph) { $lookup{$node} = $n++ if ! defined $lookup{$node}; for (@{$graph->{$node}}) { $lookup{$_} = $n++ if ! defined $lookup{$_}; } } return %lookup; }

Cheers - L~R


In reply to Re^7: Finding All Paths From a Graph From a Given Source and End Node by Limbic~Region
in thread Finding All Paths From a Graph From a Given Source and End Node by neversaint

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.