matrix_path_2-ways_best.pl 1015 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 08 August 2016
  5. # Website: https://github.com/trizen
  6. # Find the best-minimum path-sum from the top-left of a matrix, to the bottom-right.
  7. # Inspired by: https://projecteuler.net/problem=81
  8. # The path moves only right and down.
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. use List::Util qw(min);
  13. use Memoize qw(memoize);
  14. memoize('path');
  15. my @matrix = (
  16. [131, 673, 234, 103, 18],
  17. [201, 96, 342, 965, 150],
  18. [630, 803, 746, 422, 111],
  19. [537, 699, 497, 121, 956],
  20. [805, 732, 524, 37, 331],
  21. );
  22. my $end = $#matrix;
  23. sub path {
  24. my ($i, $j) = @_;
  25. if ($i < $end and $j < $end) {
  26. return $matrix[$i][$j] + min(path($i + 1, $j), path($i, $j + 1));
  27. }
  28. if ($i < $end) {
  29. return $matrix[$i][$j] + path($i + 1, $j);
  30. }
  31. if ($j < $end) {
  32. return $matrix[$i][$j] + path($i, $j + 1);
  33. }
  34. $matrix[$i][$j];
  35. }
  36. say path(0, 0);