081 Path sum two ways.pl 597 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # usage: perl problem_081.pl < p081_matrix.txt
  6. # https://projecteuler.net/problem=81
  7. use 5.010;
  8. use List::Util qw(min);
  9. use Memoize qw(memoize);
  10. memoize('path');
  11. my @matrix;
  12. while (<>) {
  13. push @matrix, [split(/,/)];
  14. }
  15. my $end = $#matrix;
  16. sub path {
  17. my ($i, $j) = @_;
  18. my @paths;
  19. if ($i < $end) {
  20. push @paths, path($i + 1, $j);
  21. }
  22. if ($j < $end) {
  23. push @paths, path($i, $j + 1);
  24. }
  25. $matrix[$i][$j] + (min(@paths) || 0);
  26. }
  27. say path(0, 0);