FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/cpp/Graphs/prerequisites.cpp at main · iamthatdev/coding-interview-patterns · GitHub
iamthatdev
/
coding-interview-patterns
Public
forked from
ByteByteGoHq/coding-interview-patterns
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
cpp
/
Graphs
/
prerequisites.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (38 loc) · 1.22 KB
Breadcrumbs
coding-interview-patterns
/
cpp
/
Graphs
/
prerequisites.cpp
Copy path
File metadata and controls
39 lines (38 loc) · 1.22 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#
include
<
vector
>
#
include
<
deque
>
bool
prerequisites
(
int
n, std::vector<std::vector<
int
>>& prerequisites) {
std::vector<std::vector<
int
>>
graph
(n);
std::vector<
int
>
inDegrees
(n,
0
);
//
Represent the graph as an adjacency list and record the in-degree
//
of each course.
for
(
auto
& p : prerequisites) {
int
prerequisite = p[
0
];
int
course = p[
1
];
graph[prerequisite].
push_back
(course);
inDegrees[course]++;
}
std::deque<
int
> queue;
//
Add all courses with an in-degree of 0 to the queue.
for
(
int
i =
0
; i < n; i++) {
if
(inDegrees[i] ==
0
) {
queue.
push_back
(i);
}
}
int
enrolledCourses =
0
;
//
Perform topological sort.
while
(!queue.
empty
()) {
int
node = queue.
front
();
queue.
pop_front
();
enrolledCourses++;
for
(
int
neighbor : graph[node]) {
inDegrees[neighbor]--;
//
If the in-degree of a neighboring course becomes 0, add
//
it to the queue.
if
(inDegrees[neighbor] ==
0
) {
queue.
push_back
(neighbor);
}
}
}
//
Return true if we've successfully enrolled in all courses.
return
enrolledCourses == n;
}
Back
|
FazBrowse Home
|
New Git URL