roc-charts 开发笔记:JS 查找图中连接两点的所有路径算法

1、把图看成以起点为根节点的树

2、使用深度遍历算法遍历路径

3、遍历到节点为目标节点时,保存这条路径

    find2PointsPath(sourceId, targetId) {
        const { nodesKV } = this.chart.getStore();  // 节点集合
        let pathArr = [];  // 保存找到的所有路径

        const findPath = (sourceId, targetId, pathNodes = []) => {
            pathNodes = [...pathNodes];  // 存储当前路径的节点。拷贝一下,避免引用传递导致递归调用时相互影响。
            pathNodes.push(sourceId);
            // 找到终点,保存路径退出
            if (sourceId === targetId) {
                pathArr.push(pathNodes);
                return;
            }

            const node = nodesKV[sourceId];
            // 取出相邻的节点
            const neighborNodes = { ...gof(node, {})('childrenKV')(), ...gof(node, {})('parentsKV')() };
            for (let id in neighborNodes) {
                // 没在已探寻中的才递归探寻,避免图中的环导致循环探寻
                if (!pathNodes.includes(id)) {
                    findPath(id, targetId, pathNodes);
                }
            }
        };
        findPath(sourceId, targetId);

        // 路径长度由短到长排序
        pathArr.sort((path1, path2) => {
            return path1.length - path2.length;
        });

        return pathArr;
    }

原文地址:https://www.cnblogs.com/3body/p/9593035.html