for my $node ($graph->nodes) { my @paths = $graph->find_shortest_paths_starting_from($node); # Now, suppose @paths is an array containing arrays of # nodes that are the actual nodes on the shortest paths, # with the first being $node and the last being the end of # the path. For instance, [ $node, $other_node, ..., $end_node ] # for the shortest path from $node to $end_node. # Next, for each endpoint, try to find a path back, but # remove the nodes from consideration that are on the # known shortest path. This is to prevent the algorithm # from re-discovering the shortest path, and will ensure # that the two possible found paths are mutually exclusive, # i.e. do not contain same nodes. (Otherwise you would have # an even shorter cycle... could this be used for our benefit?) for my $path (@paths) { my $new_graph = $graph->copy; # Slice away the first and last nodes, as they are still of # interest to us. $new_graph->remove_nodes(@$path[1 .. $#{@$path}-1]); my @paths_back = $new_graph->find_shortest_paths_starting_from($path->[-1]); for my $path_back (@paths_back) { if ($path_back->[-1] eq $node) { print "We have a cycle involving $node!\n"; } } } }