[英]More efficient way of running a random traversal of a directed graph with Networkx
我试图通过有向网络x图模拟随机遍历。 伪代码如下
Create graph G with nodes holding the value true or false.
// true -> visited, false -> not visited
pick random node N from G
save N.successors as templist
while true
nooptions = false
pick random node N from templist
while N from templist has been visited
remove N from templist
pick random node N from templist
if templist is empty
nooptions = true
break
if nooptions = true
break
save N.successors as templist
除了创建临时列表和删除元素(如果它们被标记为已访问)之外,是否有更有效的方法将路径标记为已行进?
编辑
该算法的目标是在图中随机选择一个节点。 选择该节点的随机后继/子节点。 如果没有访问,请转到那里并将其标记为已访问。 重复,直到没有继承人/孩子或没有未访问的继任者/孩子
根据图形的大小,您可以使用内置的all_pairs_shortest_path
函数。 那么你的功能基本上是:
G = nx.DiGraph()
<add some stuff to G>
# Get a random path from the graph
all_paths = nx.all_pairs_shortest_path(G)
# Choose a random source
source = random.choice(all_paths.keys())
# Choose a random target that source can access
target = random.choice(all_paths[source].keys())
# Random path is at
random_path = all_paths[source][target]
似乎没有办法从我看到的source
开始生成随机路径,但python代码是可访问的,并且我认为添加该功能将是直截了当的。
另外两种可能更快但更复杂/手动的可能性是使用bfs_successors
,它执行广度优先搜索,并且应该只在列表中包含一次目标节点。 格式不是100%肯定,所以可能不方便。
您还可以生成bfs_tree
,它生成一个子图,其中没有循环到它可以到达的所有节点。 那可能实际上更简单,也可能更短?
# Get random source from G.node
source = random.choice(G.node)
min_tree = nx.bfs_tree(G, source)
# Accessible nodes are any node in this list, except I need to remove source.
all_accessible = min_tree.node.keys()
all_accessible.remove(source)
target = random.choice(all_accessible.node.keys())
random_path = nx.shortest_path(G, source, target)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.