码迷,mamicode.com
首页 > 其他好文 > 详细

Course Schedule

时间:2015-05-07 16:04:49      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

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用于判断是否有环。学习了。

Course Schedule

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4485006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!