your 代码可能包含无限递归如果两个节点之间存在环路。例如:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([(1,2), (2,1)])
def activate_nodes(g, node):
for pred in g.predecessors(node):
activate_nodes(g, pred)
activate_nodes(G, 1)
RuntimeError: maximum recursion depth exceeded
如果其中一个图表上有可能的循环,您最好将每个节点标记为已访问或更改图表上的边以使其没有循环。
假设您的图表上没有循环,这里是如何迭代实现算法的示例:
import networkx as nx
G = nx.DiGraph()
G.add_nodes_from([1,2,3])
G.add_edges_from([(2, 1), (3, 1), (2, 3)])
G.node[1]['weight'] = 1
G.node[2]['weight'] = 2
G.node[3]['weight'] = 3
def activate_node(g, start_node):
stack = [start_node]
ws = []
while stack:
node = stack.pop()
preds = g.predecessors(node)
stack += preds
print('%s -> %s' % (node, preds))
for pred in preds:
ws.append(g.node[pred]['weight'])
print('weights: %r' % ws)
return sum(ws)
print('total sum %d' % activate_node(G, 1))
此代码打印:
1 -> [2, 3]
3 -> [2]
2 -> []
2 -> []
weights: [2, 3, 2]
total sum 7
Note
您可以使用以下命令反转有向图的方向DiGraph.reverse() https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.operators.unary.reverse.html
如果您需要使用 DFS 或其他方法,您可以反转图以将前驱节点视为该节点的直接连接的邻居。使用这个,像 DFS 这样的算法可能会更容易使用。