http://qs321.pair.com?node_id=542708


in reply to Re: traversing a hash looking for path?
in thread traversing a hash looking for path?

L~R:

Since you asked in the ChatterBox for a recursive version, I thought I'd take up the challenge. Here's my take on a recursive solution:

#!/usr/bin/perl use strict; use warnings; my %net = ( '1.2.3.3' => ['1.2.3.4'], '1.2.3.4' => ['1.2.3.3', '1.2.3.5', '1.2.3.7'], '1.2.3.5' => ['1.2.3.4', '1.2.3.6', '1.2.3.7'], '1.2.3.6' => ['1.2.3.5', '1.2.3.7'], '1.2.3.7' => ['1.2.3.6', '1.2.3.4', '1.2.3.5'], ); my %visited=(); my @stack=(); print find_path('1.2.3.4', '1.2.3.6') || "no solution!"; sub find_path { my ($beg, $end) = @_; return $end if $beg eq $end; $visited{$beg}=1; for my $try (@{$net{$beg}}) { if (!defined($visited{$try})) { push @stack, $beg; my $t = find_path($try, $end); return $beg.'=>'.$t if $t; pop @stack; } } undef; }
--roboticus