如何找到可能的路径(遍历)

时间:2018-04-25 03:45:45

标签: javascript html graph-theory puzzle

如何找到从下方对象遍历的可能路径。

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循环,但我无法找到确切的逻辑。

1 个答案:

答案 0 :(得分:2)

递归对此非常有用。

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)