Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^3: find all paths of length n in a graph

by Roy Johnson (Monsignor)
on Sep 18, 2007 at 15:14 UTC ( [id://639670]=note: print w/replies, xml ) Need Help??


in reply to Re^2: find all paths of length n in a graph
in thread find all paths of length n in a graph

You'd pass in your destination node instead of desired length, and your first test would be whether you're starting at your destination. So:
sub find_path { my ($start_at, $end_at, $been_there) = (@_, {}); if ($start_at == $end_at) { return [$start_at]; } else { my @try_these = grep { ! $been_there->{$_} } @{$adjacency_list{$st +art_at}}; return map { my @cdr_list = find_path($_, $end_at, {%$been_there, $start_at = +> 1}); map [$start_at, @$_], @cdr_list; } @try_these; } }
Homework?

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^4: find all paths of length n in a graph
by karden (Novice) on Sep 19, 2007 at 00:54 UTC
    Arghh stupid me!

    Oh no, not a HW. In fact I am a little old for HWs *ashamed*. I am good with Java/C stuff but I am trying to get familiar with Perl for one of my projects so asking whatever comes into my mind. Perl's (incredible) shorthand expressions confuse me often and sometimes I spend needlessly long time trying to figure them out (else part in the code for instance). Though this time, I agree that, I did not consider enough. It was obviously too trivial. Sorry but thank you indeed!
      I wrote this in very much a LISP style, which, if you're not familiar with it, can be pretty hard to follow. The else section constructs the non-trivial solution to the problem
      1. Look at all the nodes adjacent to where we're starting. Weed out any we've already visited.
      2. Call find_path for each of those nodes and gather up the results
      3. Return the list made by prepending this node onto each of those paths

      Caution: Contents may have been coded under pressure.
        Yeah, much clearer now. Especially after figuring out what "map" does :) Thank you indeed!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://639670]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-24 06:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found