Java Classical TOPO Implementation


  • 0
    V
    public class Solution {
        public int[] findOrder(int numCourses, int[][] prerequisites) {
            int[] dependencies = new int[numCourses];
            List<Set<Integer>> graph = new ArrayList<>();
            for (int i = 0; i < numCourses; i++) graph.add(i, new HashSet<>());
            
            for (int i = 0; i < prerequisites.length; i++) {
                graph.get(prerequisites[i][1]).add(prerequisites[i][0]);
                dependencies[prerequisites[i][0]]++;
            }
            
            List<Integer> active = new ArrayList<>();
            for (int i = 0; i < numCourses; i++) {
                if (dependencies[i] == 0) active.add(i);
            }
            
            int k = 0;
            int[] topo = new int[numCourses];
            for (int i = 0; i < numCourses && (active.size() > 0); i++) {
                int u = active.get(0);
                for(int v : graph.get(u)) {
                    if (--dependencies[v] == 0) {
                        active.add(v);
                    }
                }
                topo[k++] = u;
                active.remove(0);
            }
            
            return (k == numCourses) ? topo : new int[0];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.