Questions:
Given a directed graph of N nodes and M edges (M <= 2.N). Find all the nodes that is reachable from all other nodes.
Example:
The below graph has 4 nodes and 4 edges:
Answer: Node (2) and (3) is reachable from all other nodes.
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. But it would take O(n^2).
Is there any other approach that takes O(n.logn) or less?
Here's my take on the O(n^2) approach:
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 << ' ';
}
