图技术
利用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]]