有没有办法以编程方式找到所有的源-目标组合
是的,这被称为最短路径问题,即给定由节点/顶点V连接的边E构成的图G,找到源节点和目标节点之间的最短路径。您需要指定一系列边,其中每个边将某个节点v(i)连接到另一个节点v(j)。
有几种算法可以实现解决方案。您可以使用类似于NetworkX的库,因此无需自己实现算法。例如,
import pandas as pd
df = pd.DataFrame([
(5, 1),
(3, 5),
(2, 3),
(6, 2),
], columns=['source', 'target'])
import networkx as nx
G = nx.Graph()
G.add_edges_from(df.values)
nx.shortest_path(G, source=6, target=1)
=>
[6, 2, 3, 5, 1]
找到所有的源-目标组合
NetworkX提供许多算法,您应该将其与您试图解决的特定用例匹配。要查找给定源节点和目标节点的所有可能路径,
list(nx.all_simple_paths(G, source=6, target=1))
=>
[[6, 1], [6, 2, 3, 5, 1]]
我们希望找到所有可能的源节点和路径,最终到达我们选择的目标,而不指定源节点。
import networkx as nx
dG = nx.DiGraph()
dG.add_edges_from(df.values)
source_nodes = [x for x in G.nodes_iter() if dG.out_degree(x) >= 1]
paths = [nx.shortest_path(G, source=source, target=1) for source in source_nodes]
paths
=>
[[2, 3, 5, 1], [3, 5, 1], [5, 1], [6, 2, 3, 5, 1]]