Skip to content

Instantly share code, notes, and snippets.

@sdmcraft
Created August 29, 2021 07:27
Show Gist options
  • Save sdmcraft/feb4889a6fdb96d12714637f15a16220 to your computer and use it in GitHub Desktop.
Save sdmcraft/feb4889a6fdb96d12714637f15a16220 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
class Solution {
public boolean canFinish(int numTasks, int[][] prerequisites) {
List<Integer>[] adjacencyList = new ArrayList[numTasks];
int[] prereqCount = new int[numTasks];
for (int i = 0; i < prerequisites.length; i++) {
if(adjacencyList[prerequisites[i][1]] == null) {
adjacencyList[prerequisites[i][1]] = new ArrayList<>();
}
adjacencyList[prerequisites[i][1]].add(prerequisites[i][0]);
prereqCount[prerequisites[i][0]]++;
}
boolean proceed = true;
while (proceed) {
proceed = false;
for (int i = 0; i < numTasks; i++) {
if (prereqCount[i] == 0 && adjacencyList[i] != null) {
for (int task : adjacencyList[i]) {
prereqCount[task]--;
}
adjacencyList[i] = null;
}
}
for (int i = 0; i < numTasks; i++) {
if (prereqCount[i] == 0 && adjacencyList[i] != null) {
proceed = true;
break;
}
}
}
for (int i = 0; i < numTasks; i++) {
if (adjacencyList[i] != null) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment