Thursday, January 12, 2017

Leetcode/各大家--207.201. Course Schedule I/II (DFS with adjacent list, topo)

207.210 Course Schedule I/II(DFS with adjacent list, topo)
  • Difficulty: Medium
https://leetcode.com/problems/course-schedule/
https://leetcode.com/problems/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.
参考: https://www.youtube.com/watch?v=ddTC4Zovtbc
思路: Make adjacent list & do dfs. Adjacent list is for: node -> nodes it can go to.
Use dfs to traverse the graph, mark true in stack fro each vertices visited during recursion. if in dfs, we visit a vertex twice, there is a cycle, so impossible to take course.
Once a vertex is fully traveled(final), mark it true in visited, we can skip it during loop.
Complexity: O(V+E)
关键字:dfs, topological sort, adjacent list



public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> adjList = new ArrayList<List<Integer>>(numCourses);
        for (int i = 0; i < numCourses; i++) 
            adjList.add(i, new ArrayList<Integer>());
        for (int i = 0; i < prerequisites.length; i++)
            adjList.get(prerequisites[i][1]).add(prerequisites[i][0]);//can be reversed, depend on question        
        boolean[] visited = new boolean[numCourses];//mark once vistt a node,same as hash set
        boolean[] onStack = new boolean[numCourses];//keep visited vertex on current dfs path
        Deque<Integer> st = new LinkedList<Integer>();//final topological order
        for (int i = 0; i < numCourses; i++){
            if(visited[i])continue;
            if (hasCycle(adjList, i, visited, onStack,st)){
                return new int[0];//has Cycle, return empty arr
            }
        }
        int[] res = new int[numCourses];
        int j = 0;
        while(!st.isEmpty()) res[j++]=st.pop(); 
        return res;
    }
    
    boolean hasCycle(List<List<Integer>> adjList, int i, boolean[] visited, boolean[] onStack,Deque<Integer> st) {
        visited[i] = true;
        onStack[i] = true;
        for(Integer v:adjList.get(i)){
            if (visited[v] == false) {//dfs skip visited node, eg(at 1: skip 0)
                if(hasCycle(adjList,v,visited,onStack,st))
                    return true;
            } else if (onStack[v] == true) {//dfs path visit 1 vertex twice, means having loop
                return true;
            }
        }
        onStack[i] = false;
        st.push(i);
        return false;
    }
}

No comments:

Post a Comment