[LeetCode] Minimum Number of Vertices to Reach All Nodes

1557. Minimum Number of Vertices to Reach All Nodes

Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.

Find the smallest set of vertices from which all nodes in the graph are reachable. It’s guaranteed that a unique solution exists.

Notice that you can return the vertices in any order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
vector<bool> nodes(n);
for(auto& e : edges) {
nodes[e[1]] = true;
}
vector<int> res;
for(int i = 0; i < n; i++)
if(!nodes[i])
res.push_back(i);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/02/PS/LeetCode/minimum-number-of-vertices-to-reach-all-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.