perlgraphcyclic-dependency

Finding the all cyclic dependencies in directed graph using Perl


I am looking for the solution to a problem where Perl script could detect all the cyclic nodes in a directed graph? For example, I have following graph:

A<-N<-G<-L<- A<-B<-C<-D<-E<-F<-A Be a Graph with cyclic edges. 
use strict;
use warnings;
my @graphNodes=(A,N,G,L, A,B,C,D,E,F,A );
my depEdges= dependBy(); #Let dependBy be hypothetical function that return immediate dependents.

In rest of code, I need logical help to collect all the nodes which are involved in cyclic dependencies. For instance, in my case, on node 'A', there are cyclic dependencies. How can I recursively implement dependBy function to find cyclic edges or dependencies?


Solution

  • While this is not conceptual help, it's the fastest solution: Check if someone has already found the solution. In this case, you can use the Graph module from CPAN to do that.

    use strict;
    use warnings;
    use feature 'say';
    use Graph;
    
    my $g = Graph->new;
    
    my @edges = qw(A B C D E F A);
    for (my $i =0; $i < $#edges; $i++) {
      $g->add_edge($edges[$i], $edges[$i+1]);
    }
    
    say $g;
    say "is cyclic" if $g->is_cyclic;
    say $g->find_a_cycle;
    

    This will output:

    A-B,B-C,C-D,D-E,E-F,F-A
    is cyclic
    FABCDE