082 Path sum three ways.pl 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 08 August 2016
  5. # Website: https://github.com/trizen
  6. # The minimal path sum in the 5 by 5 matrix below, by starting in any cell
  7. # in the left column and finishing in any cell in the right column, and only
  8. # moving up, down, and right; the sum is equal to 994.
  9. # Find the minimal path sum, in a 31K text file containing a 80 by 80 matrix,
  10. # from the left column to the right column.
  11. # https://projecteuler.net/problem=82
  12. # usage: perl script.pl < p082_matrix.txt
  13. use 5.010;
  14. use Memoize qw(memoize);
  15. my @matrix;
  16. while (<>) {
  17. push @matrix, [split(/,/)];
  18. }
  19. memoize('path');
  20. my $end = $#matrix;
  21. sub path {
  22. my ($i, $j, $last) = @_;
  23. $j >= $end && return $matrix[$i][$j];
  24. my @paths;
  25. if ($i > 0 and $last ne 'down') {
  26. push @paths, path($i - 1, $j, 'up');
  27. }
  28. push @paths, path($i, $j + 1, 'ok');
  29. if ($i < $end and $last ne 'up') {
  30. push @paths, path($i + 1, $j, 'down');
  31. }
  32. my $min = 'inf';
  33. foreach my $sum (@paths) {
  34. $min = $sum if $sum < $min;
  35. }
  36. $min + $matrix[$i][$j];
  37. }
  38. my $min = 'inf';
  39. foreach my $i (0 .. $end) {
  40. my $sum = path($i, 0, 'ok');
  41. $min = $sum if $sum < $min;
  42. }
  43. say $min;