Project Euler: Problem 81 – Path sum: two ways

Problem 81:

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.

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 top left to the bottom right by only moving right and down.

Idea:

This problem is identical to problem 18, except in the form of a matrix instead of tree, and I want the minimal path instead of maximum path. I modified the algorithm I used for problem 18 to go either right or down (instead of down, or down and to the right). Tested it out and it worked.

int answer = -1;
int[][] tree = EulerUtils.readMatrix("Problem_81.txt");
EulerUtils.SumTreePath path = EulerUtils.matrixPath(tree,false);
answer = path.getSum();
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *