19
3
Given a matrix consisting of positive integers, output the path with the lowest sum when traversing from the upper left element to the bottom right. You may move vertically, horizontally and diagonally. Note that it's possible to move both up/down, right/left and diagonally to all sides.
Example:
1* 9 7 3 10 2 2
10 4* 1* 1* 1* 7 8
3 6 3 8 9 5* 7
8 10 2 5 2 1* 4
5 1 1 3 6 7 9*
The path giving the lowest sum is marked with asterisks, and results in the following sum: 1+4+1+1+1+5+1+9=23.
Test cases:
1 1 1
1 1 1
Output: 3
7 9 6 6 4
6 5 9 1 6
10 7 10 4 3
4 2 2 3 7
9 2 7 9 4
Output: 28
2 42 6 4 1
3 33 1 1 1
4 21 7 59 1
1 7 6 49 1
1 9 2 39 1
Output: 27 (2+3+4+7+7+1+1+1+1)
5 6 7 4 4
12 12 25 25 25
9 4 25 9 5
7 4 25 1 12
4 4 4 4 4
Output: 34 (5+12+4+4+4+1+4)
1 1 1 1
9 9 9 1
1 9 9 9
1 9 9 9
1 1 1 1
Output: 15
2 55 5 3 1 1 4 1
2 56 1 99 99 99 99 5
3 57 5 2 2 2 99 1
3 58 4 2 8 1 99 2
4 65 66 67 68 3 99 3
2 5 4 3 3 4 99 5
75 76 77 78 79 80 81 2
5 4 5 1 1 3 3 2
Output: 67 (2+2+3+3+4+5+4+3+3+3+1+2+2+1+3+1+1+4+5+1+2+3+5+2+2)
This is code-golf so the shortest code in each language wins.
Very similar, though it doesn't allow diagonal movement. – Mego – 2017-08-18T03:32:14.527
7@WheatWizard I disagree. Apart from the mostly superficial differences that this challenge allows for diagonal movement and all positions are reachable, the other challenge requires return of the path itself rather than just the cost of the path. Unless you're using built-ins that return both, the code is not interchangeable. – beaker – 2017-08-18T16:27:44.297
@beaker I don't really see the difference. You have to find the path to know its length. The difference here is a rather small difference in output in my opinion and this challenge offers nothing new or interesting not already covered by that challenge. – Post Rock Garf Hunter – 2017-08-18T18:24:48.080
1@WheatWizard My solution here does not find the path. It could find the path, but not without a separate predecessor array and logic to avoid making a node its own predecessor. Not to mention recovering the path at the end. – beaker – 2017-08-18T18:30:50.223
@beaker The modification is rather trivial in my opinion. Regardless the question of dupes is not whether every single valid entry on one challenge can be ported over with minimal effort, its about the general case. Not only do I think most efforts here can be ported I don't think this challenge offers anything new or interesting from the other. – Post Rock Garf Hunter – 2017-08-18T18:35:24.150