Skip to content

Commit c8d8179

Browse files
committed
add: Prerequisites
1 parent ad8f899 commit c8d8179

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

java/Graphs/Prerequisites.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.ArrayDeque;
2+
import java.util.ArrayList;
3+
import java.util.HashMap;
4+
import java.util.List;
5+
import java.util.Map;
6+
import java.util.Queue;
7+
8+
public class Prerequisites {
9+
public boolean prerequisites(int n, int[][] prerequisites) {
10+
Map<Integer, List<Integer>> graph = new HashMap<>();
11+
int[] inDegrees = new int[n];
12+
// Represent the graph as an adjacency list and record the in-
13+
// degree of each course.
14+
for (int[] edge : prerequisites) {
15+
int prerequisite = edge[0];
16+
int course = edge[1];
17+
graph.putIfAbsent(prerequisite, new ArrayList<>());
18+
graph.get(prerequisite).add(course);
19+
inDegrees[course]++;
20+
}
21+
Queue<Integer> queue = new ArrayDeque<>();
22+
// Add all courses with an in-degree of 0 to the queue.
23+
for (int i = 0; i < n; i++) {
24+
if (inDegrees[i] == 0) {
25+
queue.offer(i);
26+
}
27+
}
28+
int enrolledCourses = 0;
29+
// Perform topological sort.
30+
while (!queue.isEmpty()) {
31+
int node = queue.poll();
32+
enrolledCourses++;
33+
if (graph.containsKey(node)) {
34+
for (int neighbor : graph.get(node)) {
35+
inDegrees[neighbor]--;
36+
// If the in-degree of a neighboring course becomes 0, add
37+
// it to the queue.
38+
if (inDegrees[neighbor] == 0) {
39+
queue.offer(neighbor);
40+
}
41+
}
42+
}
43+
}
44+
// Return true if we've successfully enrolled in all courses.
45+
return enrolledCourses == n;
46+
}
47+
}

0 commit comments

Comments
 (0)