Skip to content

Commit 141ca43

Browse files
Solved Course Schedule II (LeetCode 210 | Graph | Medium) and updated Readme.md (#106)
1 parent 221e62c commit 141ca43

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Diff for: C++/Course-Schedule-II.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//CPP BFS solution
2+
//Time complexity O(V+E)
3+
//Space Complexity O(V)
4+
class Solution {
5+
public:
6+
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
7+
int n=numCourses;
8+
int m=prerequisites.size();
9+
vector<int>ans;
10+
vector<int>v(n,0);
11+
vector<vector<int>>g(n);
12+
13+
14+
for(int i=0;i<m;i++){
15+
g[prerequisites[i][1]].push_back(prerequisites[i][0]);
16+
v[prerequisites[i][0]]++;
17+
}
18+
queue<int>q;
19+
for(int i=0;i<n;i++){
20+
if(v[i]==0){
21+
q.push(i);
22+
}
23+
}
24+
int c=0;
25+
while(!q.empty()){
26+
int j=q.front();
27+
q.pop();
28+
ans.push_back(j);
29+
cout<<j<<" ";
30+
c++;
31+
for(int i=0;i<g[j].size();i++){
32+
v[g[j][i]]--;
33+
//cout<<v[g[j][i]]<<" ";
34+
if(v[g[j][i]]==0){
35+
36+
q.push(g[j][i]);
37+
}
38+
}
39+
}
40+
if(ans.size()!=n){
41+
return {};
42+
}
43+
else{
44+
return ans;
45+
}
46+
}
47+
};

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
362362
| 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii/) | [C++](./C++/Critical-Path-Sum-II.cpp) | _O(V+E)_ | _O(V)_ | Medium | Graph | DFS |
363363
| 785 | [Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) | [C++](./C++/Is-Graph-Bipartite.cpp) | _O(V+E)_ | _O(V)_ | Medium | Graph | BFS |
364364
| 947 | [Most Stones Removed with Same Row or Column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/) | [C++](./C++/Most-Stones-Removed-with-Same-Row-or-Column.cpp) | _O(V)_ | _O(2V)_ | Medium | Graph | Union Find | | [C++](./C++/Most-Stones-Removed-with-Same-Row-or-Column.cpp) | _O(V)_ | _O(2V)_ | Medium | Graph | Union Find |
365+
| 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) | [C++](./C++/Course-Schedule-II.cpp) | _O(V+E)_ | _O(V)_ | Medium | Graph | BFS |
365366
<br/>
366367
<div align="right">
367368
<b><a href="#algorithms">⬆️ Back to Top</a></b>

0 commit comments

Comments
 (0)