问题描述:
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.
分析:这道题主要是看课程之间是否存在相互依赖关系,从图论角度见是否构成环。
环的入度永远不会为0,因此,本题的思想是先找出入度为0的点,然后加入到list中,然后从list中弹出,获取元素的相临节点(通过map),然后将对应节点的入度–,当为0时,加入到list中。
当list为空时,此时如果还有num不为-1,未处理,那么就表示课程之间存在环。返回false;
代码如下:400ms
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
HashMap<Integer,List<Integer>> maps = new HashMap<>();
int[] indegree = new int[numCourses];
int length = prerequisites.length;
if(length<=0)
return true;
//init Map
for(int i = 0;i<length;i++){
int first = prerequisites[i][0];
int second = prerequisites[i][1];
if(!maps.containsKey(first))
maps.put(first,new LinkedList<>());
maps.get(first).add(second);
indegree[second]++;
}
List<Integer> list = new LinkedList();
for(int i = 0;i<numCourses;i++){
if(indegree[i]==0)
list.add(i);
}
while(list.size()>0){
int val = list.get(0);
indegree[val] = -1;
list.remove(0);
if(!maps.containsKey(val))
continue;
List<Integer> tmpList = maps.get(val);
for(int i = 0;i<tmpList.size();i++){
int index = tmpList.get(i);
indegree[index]--;
if(indegree[index]==0)
list.add(index);
}
}
for(int i = 0;i<numCourses;i++)
if(indegree[i]!=-1)
return false;
return true;
}
}