roboticus,
Thank you. I have a real hard time thinking recursively for some reason. There are some things that I would want to change. For instance, letting the call stack be handled automatically by the recursion and not relying on lexicals visible at the package level. Here is my take on satisfying those two changes:
my %net = (...); # shortened for brevity sake
print find_path('1.2.3.4', '1.2.3.6', \%net);
sub find_path {
my ($beg, $end, $net, $seen, $stop, $node, $path) = @_;
if (! defined $stop) {
($node, $path) = ($beg, $beg);
$stop->{$_} = 1 for @{$net->{$end}};
}
return $path if $node eq $end;
return "$path=>$end" if $stop->{$node};
return undef if $seen->{$node}++;
for (@{$net->{$node}}) {
my $found = find_path($beg, $end, $net, $seen, $stop, $_, "$pa
+th=>$_");
return $found if $found;
}
return 'path not found';
}
I liked the iterative solution better because I could alter the search process by adjusting the
shift/
unshift and
push/
pop. I thought recursive solutions were supposed to be more elegant. Perhaps it is just because I don't know what I am doing.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.