Skip to content

Commit 62b489f

Browse files
committed
Two-Hundred-Twenty-One Commit: Add Tasks Scheduling problem to Topological Sort Section
1 parent 8f791c7 commit 62b489f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package Topological_Sort;
2+
3+
// Problem Statement: Tasks Scheduling (medium)
4+
// LeetCode Question:
5+
6+
import java.util.*;
7+
8+
public class Problem_2_Tasks_Scheduling {
9+
public boolean isSchedulingPossible(int tasks, int[][] prerequisites) {
10+
List<Integer> sortedOrder = new ArrayList<>();
11+
if (tasks <= 0)
12+
return false;
13+
14+
// a. Initialize the graph
15+
HashMap<Integer, Integer> inDegree =
16+
new HashMap<>(); // count of incoming edges for every vertex
17+
HashMap<Integer, List<Integer>> graph = new HashMap<>(); // adjacency list graph
18+
for (int i = 0; i < tasks; i++) {
19+
inDegree.put(i, 0);
20+
graph.put(i, new ArrayList<Integer>());
21+
}
22+
23+
// b. Build the graph
24+
for (int i = 0; i < prerequisites.length; i++) {
25+
int parent = prerequisites[i][0], child = prerequisites[i][1];
26+
graph.get(parent).add(child); // put the child into it's parent's list
27+
inDegree.put(child, inDegree.get(child) + 1); // increment child's inDegree
28+
}
29+
30+
// c. Find all sources i.e., all vertices with 0 in-degrees
31+
Queue<Integer> sources = new LinkedList<>();
32+
for (Map.Entry<Integer, Integer> entry : inDegree.entrySet()) {
33+
if (entry.getValue() == 0)
34+
sources.add(entry.getKey());
35+
}
36+
37+
// d. For each source, add it to the sortedOrder and subtract one from all of its
38+
// children's in-degrees if a child's in-degree becomes zero, add it to sources queue
39+
while (!sources.isEmpty()) {
40+
int vertex = sources.poll();
41+
sortedOrder.add(vertex);
42+
// get the node's children to decrement their in-degrees
43+
List<Integer> children = graph.get(vertex);
44+
for (int child : children) {
45+
inDegree.put(child, inDegree.get(child) - 1);
46+
if (inDegree.get(child) == 0)
47+
sources.add(child);
48+
}
49+
}
50+
51+
// if sortedOrder doesn't contain all tasks, there is a cyclic dependency between
52+
// tasks, therefore, we will not be able to schedule all tasks
53+
return sortedOrder.size() == tasks;
54+
}
55+
}

0 commit comments

Comments
 (0)