Sponsored
Sponsored
The nodes that have no incoming edges cannot be reached by any other nodes. Thus, these nodes must be included in the result set for ensuring all nodes in the graph are reachable. This is because they can naturally be start points of paths that reach out to other nodes.
Time Complexity: O(n + m), where n is the number of nodes and m is the number of edges.
Space Complexity: O(n) for storing incoming edges information.
1#include <vector>
2
3std::vector<int> findSmallestSetOfVertices(int n, std::vector<std::vector<int>>& edges) {
4 std::vector<bool> hasIncoming(n, false);
5 std::vector<int> result;
6 for (const auto& edge : edges) {
7 hasIncoming[edge[1]] = true;
8 }
9 for (int i = 0; i < n; ++i) {
10 if (!hasIncoming[i]) {
11 result.push_back(i);
12 }
13 }
14 return result;
15}
16
This solution uses two vectors to track nodes with incoming edges and store the results. It iterates through the edge list to update these vectors accordingly, ensuring to return only those without any incoming edges.