Monday, August 31, 2015

Leetcode: Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]
4, [[1,0],[2,0],[3,1],[3,2]]
There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].
Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
Hints:
  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.


Understand the problem:
This problem is equivalent to finding the topological order in a directed graph. According to wiki, the topological  sorting is defined as " In the field of computer science, a topological sort (sometimes abbreviated toposort[1]) or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex vu comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time."

Code (Java):
public class Solution {
    private int label;
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        if (numCourses <= 0) {
            return new int[0];
        }
        this.label = numCourses - 1;
        
        int[] result = new int[numCourses];
        
        // No prerequisites
        if (prerequisites == null || prerequisites.length == 0) {
            for (int i = 0; i < numCourses; i++) {
                result[i] = i;
            }
            
            return result;
        }
        
        // Convert the edge list to adj. list
        Map<Integer, List<Integer>> adjList = new HashMap<>();
        for (int[] edge : prerequisites) {
            if (adjList.containsKey(edge[1])) {
                List<Integer> neighbors = adjList.get(edge[1]);
                neighbors.add(edge[0]);
                adjList.put(edge[1], neighbors);
            } else {
                List<Integer> neighbors = new ArrayList<Integer>();
                neighbors.add(edge[0]);
                adjList.put(edge[1], neighbors);
            }
        }
        
        int[] visited = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            if (toplogicalSorting(i, visited, adjList, result) == false) {
                return new int[0];
            }
        }
        
        return result;
    }
    
    private boolean toplogicalSorting(int vertexId, int[] visited, 
            Map<Integer, List<Integer>> adjList,
                                   int[] result) {
        // Has been visited
        if (visited[vertexId] == -1) {
            return false;
        }
        
        // Has been added into the list
        if (visited[vertexId] == 1) {
            return true;
        }
        
        visited[vertexId] = -1;
        
        List<Integer> neighbors = adjList.get(vertexId);
        if (neighbors != null) {
            for (int neighbor : neighbors) {
                if (toplogicalSorting(neighbor, visited, 
                    adjList, result) == false) {
                    return false;
                }
            }
        }
        
        result[label--] = vertexId;
        visited[vertexId] = 1;
        
        return true;
                                       
    }
}

Update on 4/22/19: Topological sort using BFS
public class Solution {
    /*
     * @param numCourses: a total of n courses
     * @param prerequisites: a list of prerequisite pairs
     * @return: the course order
     */
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        // write your code here
        int[] ans = new int[numCourses];
        int ansIdx = numCourses - 1;
        
        if (prerequisites == null || prerequisites.length == 0) {
            for (int i = 0; i < numCourses; i++) {
                ans[i] = i;
            }
            
            return ans;
        }
        
        Map<Integer, List<Integer>> adjList = new HashMap<>();
        Map<Integer, Integer> nodeToIndegreeMap = new HashMap<>();
        
        for (int i = 0; i < numCourses; i++) {
            adjList.put(i, new ArrayList<>());
            nodeToIndegreeMap.put(i, 0);
        }
        
        for (int[] prerequisite : prerequisites) {
            List<Integer> neighbors = adjList.get(prerequisite[0]);
            neighbors.add(prerequisite[1]);
            
            int indegree = nodeToIndegreeMap.get(prerequisite[1]);
            indegree += 1;
            nodeToIndegreeMap.put(prerequisite[1], indegree);
        }
        
        // get all nodes with 0 indegree
        //
        Queue<Integer> queue = new LinkedList<>();
        for (Integer node : nodeToIndegreeMap.keySet()) {
            if (nodeToIndegreeMap.get(node) == 0) {
                queue.offer(node);
            }
        }
        
        while (!queue.isEmpty()) {
            int curNode = queue.poll();
            ans[ansIdx--] = curNode;
            
            for (int neighbor : adjList.get(curNode)) {
                int indegree = nodeToIndegreeMap.get(neighbor);
                indegree -= 1;
                nodeToIndegreeMap.put(neighbor, indegree);
                
                if (indegree == 0) {
                    queue.offer(neighbor);
                }
            }
        }
        
        if (ansIdx > 0) {
            return new int[0];
        }
        
        return ans;
    }
}

No comments:

Post a Comment