Skip to content

Commit 4e52aa9

Browse files
committed
Leetcode - Minimum Number of Vertices to Reach All Nodes
1 parent 30bedef commit 4e52aa9

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Leetcode Top Interview Questions/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@
104104
- [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) - [Cpp Solution](./solutions/Populating%20Next%20Right%20Pointers%20in%20Each%20Node.cpp)
105105
- [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) - [Cpp Solution](./solutions/Kth%20Smallest%20Element%20in%20a%20BST.cpp)
106106
- [Number of Islands](https://leetcode.com/problems/number-of-islands/) - [Cpp Solution](./solutions/Number%20of%20Islands.cpp)
107+
- [Minimum Number of Vertices to Reach All Nodes](https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/) - [Cpp Solution](./solutions/Minimum%20numberof%20vertices.cpp)
107108

108109
### 4. Backtracking
109110

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// 1557. Minimum Number of Vertices to Reach All Nodes
2+
3+
// 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.
4+
5+
// Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
6+
7+
// Notice that you can return the vertices in any order.
8+
9+
// Example 1:
10+
11+
12+
13+
// Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
14+
// Output: [0,3]
15+
// Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
16+
// Example 2:
17+
18+
19+
20+
// Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]
21+
// Output: [0,2,3]
22+
// Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
23+
24+
25+
// Constraints:
26+
27+
// 2 <= n <= 10^5
28+
// 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
29+
// edges[i].length == 2
30+
// 0 <= fromi, toi < n
31+
// All pairs (fromi, toi) are distinct.
32+
33+
class Solution {
34+
public:
35+
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
36+
vector<int> temp(n, 0);
37+
for (int i=0;i<edges.size();i++){
38+
temp[edges[i][1]]++;
39+
}
40+
vector<int>ans;
41+
for (int i=0;i<n;i++){
42+
if (temp[i]==0){
43+
ans.push_back(i);
44+
}
45+
}
46+
return ans;
47+
}
48+
};

0 commit comments

Comments
 (0)