Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. public static void main(String[] args) {
  2.         System.out.println(canFinish(4, new String[][] {{"3", "0"}, {"0", "1"}}));
  3.         System.out.println(canFinish(4, new Integer[][] {{3, 0}, {0, 1}}));
  4.     }
  5.  
  6.  
  7.     public static <T> boolean canFinish(int numCourses, T[][] prerequisites) {
  8.         int rescount = 0;
  9.         //build graph using adjacency list. array of arraylists.
  10.         Map< T, ArrayList<T>> graph = new HashMap<>();
  11.         Map<T, Integer> inDegrees = new HashMap<>(numCourses);
  12.  
  13.         //add the edges to the graph.
  14.         for (int i = 0; i < prerequisites.length; i++) {
  15.             T firstClass = prerequisites[i][0];
  16.             T secondClass = prerequisites[i][1];
  17.             graph.putIfAbsent(firstClass, new ArrayList<>());
  18.             graph.get(firstClass).add(secondClass);
  19.             graph.putIfAbsent(secondClass, new ArrayList<>());
  20.             //since second class depends on first class, increase the indegree of second class.
  21.             inDegrees.putIfAbsent(firstClass, 0);
  22.             inDegrees.putIfAbsent(secondClass, 0);
  23.  
  24.             inDegrees.put(secondClass, inDegrees.get(secondClass) + 1);
  25.         }
  26.  
  27.         Stack< T > stack = new Stack < > ();
  28.         for (T key: inDegrees.keySet()) {
  29.             if (inDegrees.get(key)==0) {
  30.                 stack.push(key);
  31.             }
  32.         }
  33.  
  34.         //DFS basically
  35.         while (stack.size() > 0) {
  36.             T a = stack.pop();
  37.             rescount++;
  38.             //neighbors
  39.             for (T node: graph.get(a)) {
  40.                 inDegrees.put(node, inDegrees.get(node)- 1);
  41.                 if (inDegrees.get(node) == 0) {
  42.                     stack.push(node);
  43.                 }
  44.             }
  45.         }
  46.  
  47.  
  48.         if (rescount == numCourses || (inDegrees.size() == rescount)) {
  49.             return true;
  50.         }
  51.  
  52.         if (inDegrees.size() == 0)  {
  53.             return true;
  54.         }
  55.  
  56.         return false;
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement