forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request 7oSkaaa#1103 from aboelsooud/main
add the 18'th day problem solution
- Loading branch information
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
...Reach All Nodes/18- Minimum Number of Vertices to Reach All Nodes (Mahmoud Aboelsoud).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
// Author: Mahmoud Aboelsoud | ||
|
||
class Solution { | ||
public: | ||
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) { | ||
// to find the minimum number of vertices to reach all nodes we need to find the nodes with zero in degree | ||
// because we can reach all nodes from the nodes with zero in degree | ||
// we can do that by counting the in degree of each node | ||
// then loop over the nodes and add the nodes with zero in degree to the answer | ||
|
||
// in_degree: in_degree[i] -> the in degree of node i | ||
// ans: the answer | ||
vector<int> in_degree(n), ans; | ||
|
||
// count the in degree of each node | ||
for(auto&i: edges) in_degree[i[1]]++; | ||
|
||
// loop over the nodes and add the nodes with zero in degree to the answer | ||
for(int i = 0; i < n; i++){ | ||
if(!in_degree[i]) ans.emplace_back(i); | ||
} | ||
|
||
// return the answer | ||
return ans; | ||
} | ||
}; |