Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: Depth First Search through Digraph Results in Memory Leak

by Hofmator (Curate)
on Jan 09, 2004 at 09:09 UTC ( #320051=note: print w/replies, xml ) Need Help??

in reply to Depth First Search through Digraph Results in Memory Leak

I just noted a different bug in your code, in sub DFS

$explored->{$node->{_id}}++; foreach my $link (@{$node->{_outlinks}}) { $do_search->($link->{_to}) unless ($explored->{$link->{_id}}); }
should be
$explored->{$node->{_id}}++; foreach my $link (@{$node->{_outlinks}}) { $do_search->($link->{_to}) unless ($explored->{$link->{_to}{_id}}); # we stored the node id, not the link id in $explored ^^^^^ }

-- Hofmator

Replies are listed 'Best First'.
Re: Re: Depth First Search through Digraph Results in Memory Leak
by djantzen (Priest) on Jan 09, 2004 at 13:32 UTC

    I think that's okay. I'm using the algorithm from Goodrich & Tamassia's Data Structures and Algorithms in Java pg. 377. In pseudocode:

    Mark vertex v as marked.
    for each outgoing edge (v, w) of v do
    if vertex w has not been visited
    then recursively call DFS(w).

    Which makes sense to me since the objective is to locate all reachable vertices. Imagine the case where you had more than one edge connecting two vertices. You'd end up counting all the paths to a node but that isn't the goal, well at least not a transitive closure anyway.

    "The dead do not recognize context" -- Kai, Lexx

      Ok, first to get the terminology straight, 'node' eq 'vertex' and 'edge' eq 'link'.

      In your code both nodes and links have an id. Let's look at your original code:

      # this marks the current vertex $explored->{$node->{_id}}++; foreach my $link (@{$node->{_outlinks}}) { # $link isa Link, so $link->{_id} is the id of the link, # not of the vertex!! $do_search->($link->{_to}) unless ($explored->{$link->{_id}}); }
      Yes, your algorithm is fine, it's just the implementation that has a little bug in it. Here's my (correct) code again, this time written explicitly:
      $explored->{$node->{_id}}++; foreach my $link (@{$node->{_outlinks}}) { my $new_node = $link->{_to}; $do_search->($new_node) unless ($explored->{$new_node->{_id}}); }

      -- Hofmator

        Whoops, my mistake. The example was simple enough not to affect the outcome but you're quite right. Fortunately my real code doesn't contain that error.

        "The dead do not recognize context" -- Kai, Lexx

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://320051]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2018-07-17 02:32 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (353 votes). Check out past polls.