基于深度/广度遍历求有向无环图中目标节点到其他节点的全路径

图技术

利用neo4j、networkx、dgl、python做图分析挖掘

【1】最短路径算法dijkstra
【2】基于networkx的隐性集团关系识别模型
【3】基于Neo4j的担保社群型态分析挖掘


基于深度/广度遍历求有向无环图中目标节点到其他节点的全路径

前言

对于有向无环图,如何求一个点到图中其他点的全路径呢?
在这里插入图片描述

1.算法说明

graph

g r a p h 使用字典表示, g r a p h [ i ] 表示节点 i 的邻居节点 graph使用字典表示,graph[i]表示节点i的邻居节点 graph使用字典表示,graph[i]表示节点i的邻居节点

target

t a r g e t 表示目标节点 target表示目标节点 target表示目标节点

2.深度遍历算法步骤

  • 初始化单点路径solopath、全路径allpaths;
  • 将目标节点作为单条路径的起始节点;
  • 遍历目标节点的邻居节点;
    • 判断单条路径是否在全路径中,如果不在,则单条路径追加到全路径;
    • 判断邻居节点是否在单条路径中,如果不在,则邻居节点追加到单条路径;
    • 判断单条路径是否在全路径中,如果不在,则单条路径追加到全路径;
    • 邻居节点作为起始节点进行深度遍历。

3.脚本实现

#构造一张图
graph = {}
graph[1] = [2, 7, 8]
graph[2] = [3, 6]
graph[3] = [4, 5]
graph[8] = [9, 12]
graph[9] = [10, 11]
allpaths = []
solopath = []
def dfs(target):
    if target in graph:
        for neighbor in graph[target]:
            if solopath not in allpaths:
                allpaths.append(solopath[:])
            if neighbor not in solopath:
                solopath.append(neighbor)
            if solopath not in allpaths:
                allpaths.append(solopath[:])
            dfs(neighbor)
            solopath.pop()
solopath.append(1)
dfs(1)
allpaths.sort(key=lambda x: len(x), reverse=False)
print(allpaths)
#[[1], [1, 2], [1, 7], [1, 8], [1, 2, 3], [1, 2, 6], [1, 8, 9], [1, 8, 12], [1, 2, 3, 4], [1, 2, 3, 5], [1, 8, 9, 10], [1, 8, 9, 11]]

4.广度遍历代码

graph = {}
graph[1] = [2, 7, 8]
graph[2] = [3, 6]
graph[3] = [4, 5]
graph[8] = [9, 12]
graph[9] = [10, 11]
#起始节点
#存放路径结果
path = [[1]]
paths = [[1]]
#遍历
while path:
    tmp = path.pop()
    if tmp[-1] in graph:
        for i in graph[tmp[-1]]:
            other = tmp.copy()
            other.append(i)
            paths.append(other)
            path.append(other)
paths.sort(key=lambda x: len(x), reverse=False)
print(paths)
#[[1], [1, 2], [1, 7], [1, 8], [1, 8, 9], [1, 8, 12], [1, 2, 3], [1, 2, 6], [1, 8, 9, 10], [1, 8, 9, 11], [1, 2, 3, 4], [1, 2, 3, 5]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值