JavaScript 查找圖中鏈接兩點的全部路徑算法

一、把圖當作以起點爲根節點的樹node

二、使用深度遍歷算法遍歷路徑算法

三、遍歷到節點爲目標節點時,保存這條路徑this

    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;
    }
相關文章
相關標籤/搜索