Javascript 如何找到可能的路径(遍历)
如何从对象下方找到可能的路径Javascript 如何找到可能的路径(遍历),javascript,html,graph-theory,Javascript,Html,Graph Theory,如何从对象下方找到可能的路径 var pathObject = { A :["B"], B :["C", "D"], D :["E"], C :["F", "E"], E :["G"], F :["G"], G :["H"], H :[]
var pathObject = {
A :["B"],
B :["C", "D"],
D :["E"],
C :["F", "E"],
E :["G"],
F :["G"],
G :["H"],
H :[]
}
预期产出为:
[
["A", "B", "C", "F", "G", "H"],
["A", "B", "D", "E", "G", "H"],
["A", "B", "C", "E", "G", "H"]
];
如何做到这一点。。我尝试过使用while循环,但找不到确切的逻辑。递归在这方面很有用
var pathObject = {
A :["B"],
B :["C", "D"],
D :["E"],
C :["F", "E"],
E :["G"],
F :["G"],
G :["H"],
H :[]
}
var paths = []
function findPath(data, currentPath, currentPoint) {
currentPath.push(currentPoint);
if(data[currentPoint].length == 0) {
paths.push(currentPath)
} else {
data[currentPoint].map(nextPoint => {
findPath(data, currentPath.slice(0), nextPoint)
})
}
}
findPath(pathObject, [], "A");
console.log(paths)
递归在这方面很有用
var pathObject = {
A :["B"],
B :["C", "D"],
D :["E"],
C :["F", "E"],
E :["G"],
F :["G"],
G :["H"],
H :[]
}
var paths = []
function findPath(data, currentPath, currentPoint) {
currentPath.push(currentPoint);
if(data[currentPoint].length == 0) {
paths.push(currentPath)
} else {
data[currentPoint].map(nextPoint => {
findPath(data, currentPath.slice(0), nextPoint)
})
}
}
findPath(pathObject, [], "A");
console.log(paths)
请发布您尝试过的代码/逻辑,并突出显示您认为错误的地方。@JasonCust我刚刚尝试过,但没有开始。。。在开始解决这个难题时,我感到困惑。请发布您尝试过的代码/逻辑,并强调您认为错误的地方。@JasonCust我刚刚尝试过,但没有开始。。。在开始解决这个难题时,我感到困惑。