freeCodeCamp Challenge Guide: Problem 82: Path sum: three ways

Problem 82: Path sum: three ways


Solutions

Solution 1 (Click to Show/Hide)
function pathSumThreeWays(matrix) {
  function makeMinimumMoveFromUpOrRight(row, column) {
    const curValue = matrix[row][column];
    if (values[row - 1] > values[row]) {
      return values[row] + curValue;
    }
    return values[row - 1] + curValue;
  }
  function isGoingFromDownBetter(row, column) {
    return values[row] > values[row + 1] + matrix[row][column];
  }
  const size = matrix.length;
  const values = [];
  for (let row = 0; row < size; row++) {
    values.push(matrix[row][size - 1]);
  }
  for (let column = size - 2; column >= 0; column--) {
    values[0] += matrix[0][column];
    for (let row = 1; row < size; row++) {
      values[row] = makeMinimumMoveFromUpOrRight(row, column);
    }
    for (let row = size - 2; row >= 0; row--) {
      if (isGoingFromDownBetter(row, column)) {
        values[row] = values[row + 1] + matrix[row][column];
      }
    }
  }
  return Math.min(...values);
}