Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Created April 1, 2024 01:33
Show Gist options
  • Save YuanLiou/0994f9cb8942645a9ebf4098f44aeb02 to your computer and use it in GitHub Desktop.
Save YuanLiou/0994f9cb8942645a9ebf4098f44aeb02 to your computer and use it in GitHub Desktop.
kahnAlgorithn002.java
public boolean canFinish(int numCourses, int[][] prerequisites) {
int[] indegree = new int[numCourses];
List<List<Integer>> adj = new ArrayList<>(numCourses);
for (int i = 0; i < numCourses; i++) {
adj.add(new ArrayList<>());
}
for (int[] prerequisite : prerequisites) {
adj.get(prerequisite[1]).add(prerequisite[0]);
indegree[prerequisite[0]]++;
}
Queue<Integer> queue = new LinkedList<>();
// Push all the nodes with indegree zero in the queue.
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
queue.offer(i);
}
}
int nodesVisited = 0;
while (!queue.isEmpty()) {
int node = queue.poll();
nodesVisited++;
for (int neighbor : adj.get(node)) {
// Delete the edge "node -> neighbor".
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
queue.offer(neighbor);
}
}
}
return nodesVisited == numCourses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment