Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static Map<Integer, ArrayList<Integer>> adj_list;
- static boolean[] visited;
- static boolean[] explored;
- static Stack<Integer> stack;
- static ArrayList<Integer> course_schedule(Integer n, ArrayList<ArrayList<Integer>> prerequisites) {
- // Build the graph
- adj_list = new HashMap<>();
- for (int course = 0; course < n; course++) {
- adj_list.put(course, new ArrayList<Integer>());
- }
- for (ArrayList<Integer> prerequisite : prerequisites) {
- adj_list.get(prerequisite.get(1)).add(prerequisite.get(0));
- }
- // Check if there is cycle
- visited = new boolean[n];
- explored = new boolean[n];
- for (int course = 0; course < n; course++) {
- if (!visited[course]) {
- if (isCyclic(course)) {
- return new ArrayList<Integer>(Arrays.asList(-1));
- }
- }
- }
- //Apply topological sort
- stack = new Stack<Integer>();
- visited = new boolean[n];
- for (int course = 0; course < n; course++) {
- if (!visited[course]) {
- topologicalSort(course);
- }
- }
- // Retrieve the result
- ArrayList<Integer> result = new ArrayList<Integer>();
- while (!stack.isEmpty()) {
- result.add(stack.pop());
- }
- return result;
- }
- /**
- * This function is used to check the cycles in a DAG.
- * This si simply a DFS traversal of the graph.
- **/
- static boolean isCyclic(int course) {
- visited[course] = true;
- for (int preCourse : adj_list.get(course)) {
- if (!visited[preCourse]) {
- if (isCyclic(preCourse)) {
- return true;
- }
- } else if (!explored[preCourse]) {
- return true;
- }
- }
- explored[course] = true;
- return false;
- }
- /**
- * This function is used to perform the topological sort in a DAG.
- * It is using a stack.
- **/
- static void topologicalSort(int course) {
- visited[course] = true;
- for (int preCourse : adj_list.get(course)) {
- if (!visited[preCourse]) {
- topologicalSort(preCourse);
- }
- }
- stack.push(course);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement