您的位置:首页 > 其它

Leetcode-207: Course Schedule

2017-08-22 15:01 549 查看
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.
You may assume that there are no duplicate edges in the input prerequisites.

click to show more hints.

给出课程的门数numCourses和各个课程的先修要求,那么可以抽象出一张图(Graphy),每门课程作为一个节点(node),先修要求作为有向边(direct-edge),实际上本题是求:给出的这幅有向图中,是否存在环路?这个问题在算法导论中的拓扑排序中介绍过:有向图中如果不存在环,那么在深度搜索(DFS)的过程中不存在后向边。

那么可以直接对每个节点依次进行DFS,维护一个visited数组,来记录是否访问过节点i,这里需要注意的是,一个节点可能有多个祖先节点,我们可以学习算法导论中的DFS方法,对节点进行染色:1)没有访问过的节点染成白色;2)入栈后的节点染成灰色;3)访问后出栈的节点染成黑色。这样做的好处是,染成灰色的节点是我们当前遍历的路径下的节点,染成黑色的节点则是之前遍历过的路径节点。已经遍历过、并且不存在环路的路径节点被染成黑色,那么下次遍历到这个节点时,无需向下遍历,肯定不存在环路;如果遍历的时候访问到了灰色节点,那么说明当前的路径存在一条后向边(环路),那么直接返回false即可。

class Solution {
private int[] visited;
private Map<Integer, List<Integer>> map;

public boolean canFinish(int numCourses, int[][] prerequisites) {
if (numCourses <= 1 || prerequisites == null || prerequisites.length == 0)
return true;

visited = new int[numCourses];
map = new HashMap<>();

for (int[] pre: prerequisites) {
if (map.containsKey(pre[0])) {
map.get(pre[0]).add(pre[1]);
}
else {
List<Integer> list = new ArrayList<Integer>();
list.add(pre[1]);
map.put(pre[0], list);
}
}

for (int i = 0; i < numCourses; ++i) {
if (map.containsKey(i) && visited[i] == 0) {
if (!visit(map, i))
return false;
}
}

return true;
}

private boolean visit(Map<Integer, List<Integer>> map, int i) {
if (visited[i] == 1)
return false;
else if (visited[i] == 2 || !map.containsKey(i))
return true;

boolean res = true;

visited[i] = 1;
for (Integer next : map.get(i)) {
if (!visit(map, next)) {
res = false;
break;
}
}
visited[i] = 2;

return res;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: