![](/img/trans.png)
[英]Find all vertices reachable from a vertex of a directed graph in time O(|E| + |V|)
[英]How to find the sum weight of all edges reachable from some vertex?
您可以使用BFS或DFS来实现此目的。
total = 0
dfs (node):
if visited[node] == 1:
return
visited[node] = 1
for all u connected to node:
total += weight[node][u]
dfs(u)
请注意,我们在total += weight[node][u]
之后检查total += weight[node][u]
。
您可以使用自下而上的方法。 首先计算每个顶点的出度,现在出度为0的顶点的F [u] = 0。 现在,将所有这些顶点添加到队列Q中。
同样,您需要存储图的转置,假设它是T。
While(!Q.empty){
u=Q.front();
Q.pop();
for all edges E originating from T[u]{
F[v]+=w; (where (u,v) was the edge with w as weight)
//now remove u from the graph
outdegree[v]--;
if(outdegree[v]==0)
Q.push(v);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.