[英]Find nodes in directed graph that is reachable from all other nodes
Questions:问题:
Given a directed graph of N nodes and M edges (M <= 2.N).给定 N 个节点和 M 个边的有向图 (M <= 2.N)。 Find all the nodes that is reachable from all other nodes.
查找所有其他节点可访问的所有节点。
Example:例子:
The below graph has 4 nodes and 4 edges:下图有 4 个节点和 4 个边:
Answer: Node (2) and (3) is reachable from all other nodes.答:节点(2)和(3)可从所有其他节点到达。
P/S:附:
The only solution I came up with is to revert the graph, BFS all nodes and check if they reach all other nodes.我想出的唯一解决方案是还原图形,BFS 所有节点并检查它们是否到达所有其他节点。 But it would take O(n^2).
但这需要 O(n^2)。
Is there any other approach that takes O(n.logn) or less?有没有其他方法需要 O(n.logn) 或更少?
Here's my take on the O(n^2) approach:这是我对 O(n^2) 方法的看法:
void init(){
cin >> n >> m;
for(int i = 0; i < m; i++){
int u, v; cin >> u >> v;
adj[v].emplace_back(u);
}
}
void dfs(int u){
visited[u] = true;
for(int v : adj[u])
if(!visited[v]) dfs(v);
}
init();
for(int u = 1; u <= n; u++){
memset(visited, 0, sizeof visited);
dfs(u);
if(count(visited + 1, visited + n + 1, 1) == n) cout << u << ' ';
}
Can You share that code which take O(n^2)
?你能分享那个需要
O(n^2)
吗?
Anyway, This approach only take O(n), Which is better then O(n log n)!无论如何,这种方法只需要 O(n),这比 O(n log n) 更好!
class DirectedGraph { graph = {} constructor(directedGraph) { for (let [id, arrow] of directedGraph) this.graph[id] = { arrow, isVisited: false } } find_end_points(id) { let out = [], graph = this.graph; function go_next(id, from) { let node = graph[id]; if (node.isVisited || !node.arrow) return out.push(id) if (node.arrow == from) out.push(id); node.isVisited = true; go_next(node.arrow, id); } go_next(id, null); return out } } let directedGraph = new DirectedGraph([[2, 3], [3, 2], [1, 2], [4, 1]]); console.log(directedGraph.find_end_points(4))
You can get an O(|V| + |E|) algorithm using Tarjan's strongly connected components algorithm.您可以使用Tarjan 的强连通分量算法获得 O(|V| + |E|) 算法。 Many sample implementations are available online or in standard algorithms textbooks.
许多示例实现可在线或在标准算法教科书中获得。
Once you have the strongly connected components, the set of vertices reachable from all others is exactly the set of vertices whose strongly connected component(s) have out-degree 0 (the sinks in the graph).一旦你有了强连通分量,所有其他节点可达的顶点集合正是其强连通分量的出度为 0(图中的汇)的顶点集合。 However, there is one exception: if the condensation of the graph (the new graph induced by the strongly connected components) is not connected, there are no such vertices.
但是,有一个例外:如果图的凝聚(由强连通分量引起的新图)不连通,则不存在这样的顶点。 You can test the connectivity of a directed acyclic graph in O(|V|) time, by running a breadth-first search from any in-degree 0 vertex.
您可以通过从任何入度为 0 的顶点运行广度优先搜索,在 O(|V|) 时间内测试有向无环图的连通性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.