Path with smallest sum in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

JavaScript function that takes in a 2-D array of numbers as the first and the only argument.

Our function should find paths from the 2-D array by picking exactly one element from each row, and no two elements picked from adjacent rows should be in the same column. Out of all these paths, our function should return the sum of that path that has the minimum sum.

For example, if the input to the function is −

const arr = [
[4, 7, 1],
[2, 8, 3],
[5, 6, 9]
]

Then the output should be −

const output = 9;

Output Explanation

Because all the valid paths are −

 4, 8, 9 4, 8, 6 4, 3, 6 4, 3, 5 7, 2, 6 7, 2, 9 7, 3, 6 7, 3, 5 1, 2, 6 1, 2, 9 1, 8, 9 1, 8, 5

And out of these all, [1, 2, 6] has the least sum of 9.

Example

The code for this will be −

const arr = [
[4, 7, 1],
[2, 8, 3],
[5, 6, 9]
]
const minimumPathSum = (arr = []) => {
let first = [0, null];
let second = [0, null];
for(let row = arr.length - 1; row >= 0; row--){
let curr1 = null;
let curr2 = null;
for(let column = 0; column < arr[row].length; column++){
let currentSum = arr[row][column];
if(column !== first[1]){
currentSum += first[0];
}else{
currentSum += second[0];
};
if(curr1 === null || currentSum < curr1[0]){
curr2 = curr1;
curr1 = [currentSum, column];
}else if(curr2 === null || currentSum < curr2[0]){
curr2 = [currentSum, column];
};
};
first = curr1;
second = curr2;
};
return first[0];
};
console.log(minimumPathSum(arr));

Output

And the output in the console will be −

9
Published on 07-Apr-2021 07:24:49