LeetCode 207 - Course Schedule

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, is it possible for you to finish all courses?

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 it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Hints:
  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. There are several ways to represent a graph. For example, the input prerequisites is a graph represented by a list of edges. Is this graph representation appropriate?
  3. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  4. Topological sort could also be done via BFS.

Solution 1:

DFS

class DiGraph {
    int V;
    List<Integer>[] adj;
    public DiGraph(int v) {
        V = v;
        adj = new List[v];
        for(int i=0; i<v; i++) {
            adj[i] = new ArrayList<>();
        }
    }
    public void addEdge(int u, int v) {
        adj[u].add(v);
    }
}
public boolean canFinish(int numCourses, int[][] prerequisites) {
    DiGraph g = new DiGraph(numCourses);
    for(int[] courses:prerequisites) {
        g.addEdge(courses[1], courses[0]);
    }
    boolean[] visited = new boolean[numCourses];
    for(int i=0; i<numCourses; i++) {
        if(!canFinish(g, visited, i)) return false;
    }
    return true;
}

private boolean canFinish(DiGraph g, boolean[] visited, int u) {
    visited[u] = true;
    for(int v:g.adj[u]) {
        if(visited[v] || !canFinish(g, visited, v)) return false;
    }
    visited[u] = false;
    return true;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2208985