// you’re reading...

Project Euler Solutions

Project Euler Problem 82 Solution

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Problem Description

NOTE: This problem is a more challenging version of Problem 81.

The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red; the sum is equal to 994.

131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331

Find the minimal path sum, in matrix.txt (right click and ‘Save Link/Target As…’), a 31K text file containing a 80 by 80 matrix, from the left column to the right column.

Analysis

This is using the same technique that solved problem 18, 67, 81 & 83. We no longer have a fixed starting and ending point so we need to track the starting points to a vector. From there we “bubble” the minimum sums by moving from left to right.

Solution

Runs < 1 second in Perl.

@rows = map { [split /,/] } <DATA>;
$nrows = $#rows;
push @cost, $rows[$_][0] for (0..$nrows);
 
for $x (1..$nrows) {
  for $y (0..$nrows) {
    $cost[$y] = min_n($cost[$y], $cost[$y-1]) + $rows[$y][$x];
  }
  for $y (reverse (0..$nrows-2)) {
    $cost[$y] = min_n($cost[$y], $cost[$y+1] + $rows[$y][$x]);
  }
}
print min_n(@cost);
 
sub min_n { return (sort {$a<=>$b} grep {defined} @_)[0] }
__DATA__
131, 673, 234, 103, 18 
201, 96, 342, 965, 150 
630, 803, 746, 422, 111 
537, 699, 497, 121, 956 
805, 732, 524, 37, 331

Comments

  • We’ve included the sample matrix as an example.
  • The first line of the program reads the data file, which is appended to the end of the program after the __DATA__ separator, into a two dimensional array named @rows. $nrows is the last index of the array so in this case 4.
  • Check here for more information on the min_n function.

Discussion

No comments for “Project Euler Problem 82 Solution”

Post a comment