g0201_0300.s0210_course_schedule_ii.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java17 Show documentation
Show all versions of leetcode-in-java17 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
package g0201_0300.s0210_course_schedule_ii;
// #Medium #Top_Interview_Questions #Depth_First_Search #Breadth_First_Search #Graph
// #Topological_Sort
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public int[] findOrder(int numCourses, int[][] prerequisites) {
Map> graph = new HashMap<>();
for (int i = 0; i < numCourses; i++) {
graph.put(i, new ArrayList<>());
}
for (int[] classes : prerequisites) {
graph.get(classes[0]).add(classes[1]);
}
List output = new ArrayList<>();
Map visited = new HashMap<>();
for (int c : graph.keySet()) {
if (dfs(c, graph, visited, output)) {
return new int[0];
}
}
int[] res = new int[output.size()];
for (int i = 0; i < output.size(); i++) {
res[i] = output.get(i);
}
return res;
}
private boolean dfs(
int course,
Map> graph,
Map visited,
List output) {
if (visited.containsKey(course)) {
return visited.get(course);
}
visited.put(course, true);
for (int c : graph.get(course)) {
if (dfs(c, graph, visited, output)) {
return true;
}
}
visited.put(course, false);
output.add(course);
return false;
}
}