I have a code that currently only finds 2 possible paths. How can I modify it to find all possible paths?
For example, starting with the first array [1, 32]
, pick a number like 32
.
Next, look at the following array: [11, 21, 24, 27, 35, 37, 65]
. A valid step would be any number greater than your current step from this array. So, 35
, 37
, and 65
are all valid steps.
Continue building the path by stepping onto the subsequent arrays in order (from top to bottom) until you reach the last one.
'use strict';
const matrix = [
[1, 32],
[11, 21, 24, 27, 35, 37, 65],
[17, 22, 25, 51, 57, 63],
[18, 56]
];
function findPaths(arrays) {
const paths = [];
for (let i = 0; i < arrays[0].length; i++) {
const path = [arrays[0][i]];
for (let j = 1; j < arrays.length; j++) {
for (let y = 0; y < arrays[j].length; y++) {
if (path[Math.max(0, path.length - 1)] < arrays[j][y]) {
path.push(arrays[j][y]);
break;
}
}
}
paths.push(path);
}
return paths;
}
const result = findPaths(matrix);
console.log(result); // [ [ 1, 11, 17, 18 ], [ 32, 35, 51, 56 ] ]