您的位置:首页 > 其它

207. Course Schedule

2016-06-25 21:34 357 查看
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.

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how
a graph is represented.

就是给一个有向图,检测是否存在环。

boolean hascycle=false;
boolean[] onstack,used;

public boolean canFinish(int numCourses, int[][] prerequisites)
{
if(numCourses<1)
return true;

int m=prerequisites.length;
if(m<1)
return true;
ArrayList<Integer>[] adjlist=new ArrayList[numCourses];
for(int i=0;i<numCourses;i++)
adjlist[i]=new ArrayList<>();

for(int i=0;i<m;i++)
adjlist[prerequisites[i][1]].add(prerequisites[i][0]);

onstack=new boolean[numCourses];
used=new boolean[numCourses];

for(int i=0;i<numCourses;i++)
if(!used[i])
dfs(i,adjlist);

return !hascycle;

}

private void dfs(int i,ArrayList<Integer>[] adjlist)
{
used[i]=true;
onstack[i]=true;
for(int a : adjlist[i])
if(hascycle)
return ;
else if(!used[a])
dfs(a, adjlist);
else if(onstack[a])
{
hascycle=true;
return ;
}
onstack[i]=false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: