Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- System.out.println(canFinish(4, new String[][] {{"3", "0"}, {"0", "1"}}));
- System.out.println(canFinish(4, new Integer[][] {{3, 0}, {0, 1}}));
- }
- public static <T> boolean canFinish(int numCourses, T[][] prerequisites) {
- int rescount = 0;
- //build graph using adjacency list. array of arraylists.
- Map< T, ArrayList<T>> graph = new HashMap<>();
- Map<T, Integer> inDegrees = new HashMap<>(numCourses);
- //add the edges to the graph.
- for (int i = 0; i < prerequisites.length; i++) {
- T firstClass = prerequisites[i][0];
- T secondClass = prerequisites[i][1];
- graph.putIfAbsent(firstClass, new ArrayList<>());
- graph.get(firstClass).add(secondClass);
- graph.putIfAbsent(secondClass, new ArrayList<>());
- //since second class depends on first class, increase the indegree of second class.
- inDegrees.putIfAbsent(firstClass, 0);
- inDegrees.putIfAbsent(secondClass, 0);
- inDegrees.put(secondClass, inDegrees.get(secondClass) + 1);
- }
- Stack< T > stack = new Stack < > ();
- for (T key: inDegrees.keySet()) {
- if (inDegrees.get(key)==0) {
- stack.push(key);
- }
- }
- //DFS basically
- while (stack.size() > 0) {
- T a = stack.pop();
- rescount++;
- //neighbors
- for (T node: graph.get(a)) {
- inDegrees.put(node, inDegrees.get(node)- 1);
- if (inDegrees.get(node) == 0) {
- stack.push(node);
- }
- }
- }
- if (rescount == numCourses || (inDegrees.size() == rescount)) {
- return true;
- }
- if (inDegrees.size() == 0) {
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement