Course Schedule

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?

思路:

  拓扑排序,dfs

我的代码:

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if(numCourses<=0 || prerequisites==null || prerequisites.length==0) return true;
        HashSet<Integer>[] graph = new HashSet[numCourses];
        for(int i=0; i<numCourses; i++)
            graph[i] = new HashSet<Integer>();
        boolean[] visited = new boolean[numCourses];
        boolean[] visiting = new boolean[numCourses];
        
        for(int i=0; i<prerequisites.length; i++)
        {
            graph[prerequisites[i][1]].add(prerequisites[i][0]);
        }
        for(int i=0; i<numCourses; i++)
        {
            if(visited[i]) continue;
            if(helper(visited, visiting, graph, i) == false)    return false;
        }
        return true;
    }
    public boolean helper(boolean[] visited, boolean[] visiting, HashSet<Integer>[] graph, int j)
    {
        if(visiting[j]) return false;
        visiting[j] = true;
        
        for(Integer neighbor: graph[j])
        {
            if(visited[neighbor]) continue;
            if(helper(visited, visiting, graph, neighbor) == false) return false;
        }
        
        visiting[j] = false;
        visited[j] = true;
        return true;
    }
    
    
}
View Code

学习之处:

  这道题有思路,但是一直不会写拓扑排序,主要的纠结在于如何判断是否又环,这个人的思路很赞,通过visited判断节点是否访问过,visiting用于判断是否有环。学习了。

posted on 2015-05-07 15:17  zhouzhou0615  阅读(137)  评论(0编辑  收藏  举报

导航