![](/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.