All pastes #500892 Raw Edit

Miscellany

public text v1 · immutable
·published 2007-05-21 19:52 UTC
rendered paste body
#!/usr/bin/perl

use strict;
use Graph::Undirected;
use Graph::Traversal::DFS;
  
my $g = Graph::Undirected->new;
  
$g->add_edge('a', 'b');
$g->add_edge('b', 'c');
$g->add_edge('c', 'd');
$g->add_edge('c', 'z');
$g->add_edge('d', 'e');
$g->add_edge('c', 'q');
$g->add_edge('q', 'r');
$g->add_edge('r', 's');

# what I'd like this to return is
# a, b, c, d, e
# c, q, r, s
# c, z
# see, since c is a branch point, I want c to be part of the set returned
# by the program.

# this current code starts at 'a' and cruises along the depth first tree
#  but it doesnt exhaustively find all the branches and produce the above
# output.

my $old_node;
my $count = 0;
my @pre;

my $t = Graph::Traversal::DFS->new($g);
#i don't think this is necessary if you call $t->preorder. $t->preorder should perform the DFS and return nodes in order of encounter
#				   pre  => sub { push @pre,  $_[0] },
#				   start => 'a');

my @pre = $t->preorder;


my %done;

#are you looping through all nodes looking for nodes with more than 2 edges?
foreach my $x (@pre) {
  my $e = scalar($g->edges_from($x));
  print "X: $x $e\n";
  $done{$x} = 1;
  if ($e > 2) {
    foreach my $y ($g->edges_from($x)) {
      if ($y->[1] ne $pre[$count+1] && $done{$y->[1]} != 1) {
	print " B: $y->[1]\n";
      }
    }
  }
  $count++;
}