提问者:小点点

如何找到从第一个到最后一个数字的二维数组中的所有可能路径,其中每个步骤的值大于上一步?


到目前为止,我得到的代码只找到了2条可能的路径。我如何修改它以找到所有这些路径?

有效路径的一个示例是,从第一个数组[1,32]开始。选择一个要跳出的数字,例如32

查看下面的下一个数组:[11,21,24,27,35,37,65]。有效的步骤是大于当前步骤的任何数字。因此353765都是有效的步骤。

并通过按顺序(从上到下)在其他数组上执行步骤来继续构建路径,直到您到达最后一个数组。

'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 ] ]

共1个答案

匿名用户

我解决了。这不是最有效的解决方案,但我正在努力。

const data = [
  [1, 32],
  [11, 21, 24, 27, 35, 37, 65],
  [17, 22, 25, 51, 57, 63],
  [18, 56]
];

function findPaths(arrays) {
  const paths = [];
  const maxPaths = arrays.reduce((total, arr) => total *= arr.length || total, 1);
  for (let x = 0; x < maxPaths; x++) {
    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]) {
            if (!paths.some(p => p.toString() == [...path, arrays[j][y]].toString())) {
              path.push(arrays[j][y]);
              break;
            }
          }
        }
      }
      paths.push(path);
    }
  }
  return paths.filter(path => path.length == arrays.length).sort();
}

const result = findPaths(data);

console.log(result);

/*
[
  [ 1, 11, 17, 18 ],  [ 1, 11, 17, 56 ],
  [ 1, 11, 22, 56 ],  [ 1, 11, 25, 56 ],
  [ 1, 11, 51, 56 ],  [ 1, 21, 22, 56 ],
  [ 1, 21, 25, 56 ],  [ 1, 21, 51, 56 ],
  [ 1, 24, 25, 56 ],  [ 1, 24, 51, 56 ],
  [ 1, 27, 51, 56 ],  [ 1, 35, 51, 56 ],
  [ 1, 37, 51, 56 ],  [ 32, 35, 51, 56 ],
  [ 32, 37, 51, 56 ]
]
*/