我有一个2d数组,试图在其中寻找一些注意事项的最长序列路径。我已经遍历并创建了一个数组,该数组概述了给定点的所有可能路径:
[
{
"value": 8,
"row": 0,
"col": 0,
"paths": [{ "row": 1, "col": 0 }, { "row": 0, "col": 1 }]
},
{
"value": 2,
"row": 0,
"col": 1,
"paths": [{ "row": 1, "col": 1 }, { "row": 0, "col": 0 }]
},
{ "value": 4, "row": 0, "col": 2, "paths": [] },
{
"value": 0,
"row": 1,
"col": 0,
"paths": [
{ "row": 0, "col": 0 },
{ "row": 2, "col": 1 },
{ "row": 1, "col": 1 }
]
},
{
"value": 6,
"row": 1,
"col": 1,
"paths": [{ "row": 0, "col": 1 }, { "row": 1, "col": 2 }]
},
{
"value": 1,
"row": 1,
"col": 2,
"paths": [
{ "row": 2, "col": 2 },
{ "row": 2, "col": 1 },
{ "row": 1, "col": 1 }
]
},
{ "value": 3, "row": 2, "col": 0, "paths": [{ "row": 2, "col": 1 }] },
{
"value": 7,
"row": 2,
"col": 1,
"paths": [{ "row": 1, "col": 2 }, { "row": 2, "col": 0 }]
},
{ "value": 9, "row": 2, "col": 2, "paths": [{ "row": 1, "col": 2 }] }
]
因此对于第一个点8 -> (0,0)
,它可以转到(0,1)
和(1,0)
,在这些点中,一旦到达该点,则可能要遵循0到n条路径。我必须能够测试所有可能的路径以计算最长的链。
我可以得到它来计算一条路径,但是我非常想测试所有可能的结果。
答案 0 :(得分:0)
您可以获得一个仅包含下一项目数组的对象,并使用嵌套节点的下一个Array#flatMap
映射这些项目。为了防止出现圆形结果,您需要检入advane并仅返回到达已访问节点的路径。
因此,您需要过滤最长的链。此结果获取所有链,并使用带有分隔符的紧凑连接。
const
go = path => k => path.includes(k.toString())
? path.join('-')
: object[k].flatMap(go(path.concat(k.toString()))),
getKey = ({ row, col }) => [row, col].join('|');
var data = [{ value: 8, row: 0, col: 0, paths: [{ row: 1, col: 0 }, { row: 0, col: 1 }] }, { value: 2, row: 0, col: 1, paths: [{ row: 1, col: 1 }, { row: 0, col: 0 }] }, { value: 4, row: 0, col: 2, paths: [] }, { value: 0, row: 1, col: 0, paths: [{ row: 0, col: 0 }, { row: 2, col: 1 }, { row: 1, col: 1 }] }, { value: 6, row: 1, col: 1, paths: [{ row: 0, col: 1 }, { row: 1, col: 2 }] }, { value: 1, row: 1, col: 2, paths: [{ row: 2, col: 2 }, { row: 2, col: 1 }, { row: 1, col: 1 }] }, { value: 3, row: 2, col: 0, paths: [{ row: 2, col: 1 }] }, { value: 7, row: 2, col: 1, paths: [{ row: 1, col: 2 }, { row: 2, col: 0 }] }, { value: 9, row: 2, col: 2, paths: [{ row: 1, col: 2 }] }],
keys = Object.assign(...data.map(o => ({ [getKey(o)]: o.value }))),
object = Object.assign(...data.map(o => ({ [keys[getKey(o)]]: o.paths.map(o => keys[getKey(o)]) }))),
result = Object.keys(object).map(go([]));
console.log(result);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }