http://www.perlmonks.org?node_id=1211502


in reply to compute paths in Pascal's triangle (aka Tartaglia's one)

I've recently been playing with Graph and it seems this may be a shortest path (specifically, All-Pairs Shortest Paths (APSP)) problem? The module uses the Floyd Warshall algorithm to calculate. The following creates the graph object and then calculates shortest path and prints it. Note, it only shows 1 path - have a look at the Graph perldoc on how to get all paths. (Note: I also used Graph::Convert and Graph::Easy to get the visual; it's not required to make this work.)

UPDATE: Updated code to be more efficient

#!perl use strict; use warnings; my $MAX = 5; # how big my $TO = '3-1'; # from 0-0, where to? use Graph; my $g = Graph->new(); my @from; for my $y ( 0 .. $MAX ) { my @to; for my $x ( 0 .. $y ) { push @to, "$y-$x"; } for my $f ( 0 .. $#from ) { for my $t ( $f .. $f + 1 ) { $g->add_edge( $from[$f], $to[$t] ); } } @from = @to; } # Comment next 3 if no install Graph::Convert and Graph::Easy use Graph::Convert; my $ge = Graph::Convert->as_graph_easy($g); print $ge->as_ascii . "\n"; my $apsp = $g->APSP_Floyd_Warshall(); my @v = $apsp->path_vertices('0-0', $TO); print join ( " ", @v ) . "\n";

OUTPUT:

+-----+     +-----+     +-----+     +-----+     +-----+     +-----+
| 0-0 | --> | 1-0 | --> | 2-0 | --> | 3-0 | --> | 4-0 | --> | 5-0 |
+-----+     +-----+     +-----+     +-----+     +-----+     +-----+
  |           |           |           |           |
  |           |           |           |           |
  v           v           v           v           v
+-----+     +-----+     +-----+     +-----+     +-----+
| 1-1 | --> | 2-1 | --> | 3-1 | --> | 4-1 | --> | 5-1 |
+-----+     +-----+     +-----+     +-----+     +-----+
  |           |           |           |
  |           |           |           |
  v           v           v           v
+-----+     +-----+     +-----+     +-----+
| 2-2 | --> | 3-2 | --> | 4-2 | --> | 5-2 |
+-----+     +-----+     +-----+     +-----+
  |           |           |
  |           |           |
  v           v           v
+-----+     +-----+     +-----+
| 3-3 | --> | 4-3 | --> | 5-3 |
+-----+     +-----+     +-----+
  |           |
  |           |
  v           v
+-----+     +-----+
| 4-4 | --> | 5-4 |
+-----+     +-----+
  |
  |
  v
+-----+
| 5-5 |
+-----+

0-0 1-0 2-0 3-1