MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / prerequisites

Function prerequisites

cpp/Graphs/prerequisites.cpp:4–39  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2#include <deque>
3
4bool prerequisites(int n, std::vector<std::vector<int>>& prerequisites) {
5 std::vector<std::vector<int>> graph(n);
6 std::vector<int> inDegrees(n, 0);
7 // Represent the graph as an adjacency list and record the in-degree
8 // of each course.
9 for (auto& p : prerequisites) {
10 int prerequisite = p[0];
11 int course = p[1];
12 graph[prerequisite].push_back(course);
13 inDegrees[course]++;
14 }
15 std::deque<int> queue;
16 // Add all courses with an in-degree of 0 to the queue.
17 for (int i = 0; i < n; i++) {
18 if (inDegrees[i] == 0) {
19 queue.push_back(i);
20 }
21 }
22 int enrolledCourses = 0;
23 // Perform topological sort.
24 while (!queue.empty()) {
25 int node = queue.front();
26 queue.pop_front();
27 enrolledCourses++;
28 for (int neighbor : graph[node]) {
29 inDegrees[neighbor]--;
30 // If the in-degree of a neighboring course becomes 0, add
31 // it to the queue.
32 if (inDegrees[neighbor] == 0) {
33 queue.push_back(neighbor);
34 }
35 }
36 }
37 // Return true if we've successfully enrolled in all courses.
38 return enrolledCourses == n;
39}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected