Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. //Runtime: 6 ms, faster than 63.02% of Java online submissions for Course Schedule II.
  2. //Memory Usage: 45.6 MB, less than 85.37% of Java online submissions for Course Schedule II.
  3. class Solution {
  4.   final int PROCESSING = 1;
  5.   final int DONE = 2;
  6.   final int[] NOT_POSSIBLE = new int[0];
  7.  
  8.   public int[] findOrder(int numCourses, int[][] prerequisites) {
  9.     ArrayList<Integer>[] graph = buildGraph(numCourses,prerequisites);
  10.     int[] states = new int[numCourses];
  11.     LinkedList<Integer> answer = new LinkedList<>();
  12.    
  13.     for(int i = 0; i < numCourses; i++){
  14.       boolean cycle = dfs(graph, i, answer, states);
  15.       if(cycle) return NOT_POSSIBLE;
  16.     }
  17.     if(answer.size() != numCourses) return NOT_POSSIBLE;
  18.     int[] result = new int[numCourses];
  19.     for(int i = 0; i < numCourses; i ++) result[i] = answer.get(i);
  20.     return result;
  21.   }
  22.  
  23.   private boolean dfs(ArrayList<Integer>[] graph, int current, LinkedList<Integer> answer, int[] states){
  24.     if(states[current] == PROCESSING){
  25.       return true;
  26.     }
  27.     if(states[current] == DONE) return false;
  28.    
  29.     states[current] = PROCESSING;
  30.     for(int next : graph[current]){
  31.       if(states[next] == DONE) continue;
  32.       boolean cycle = dfs(graph, next, answer, states);
  33.       if(cycle) return true;
  34.     }
  35.     answer.add(current);
  36.     states[current] = DONE;
  37.     return false;
  38.   }
  39.  
  40.   ArrayList<Integer>[] buildGraph(int numCourses, int[][] prerequisites){
  41.     ArrayList<Integer>[] graph = new ArrayList[numCourses];
  42.     for(int i = 0 ; i < graph.length; i++) graph[i] = new ArrayList<>();
  43.     for(int[] edge : prerequisites){
  44.       graph[edge[0]].add(edge[1]);
  45.     }
  46.     return graph;
  47.   }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement