问题引入
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.
解题思路public boolean canFinish(int n, int[][] prere) {
int[][] graph = new int[n][n];
int[] degree = new int[n];
Queue<Integer> queue = new LinkedList();
for(int i = 0;i < prere.length;i++){
int re = prere[i][0];
int pr = prere[i][1];
if(graph[re][pr]==0)degree[re]++;
graph[re][pr] = 1;
}
for(int i = 0;i < n;i++){
if(degree[i]==0)
queue.offer(i);
}
int count = 0;
while(!queue.isEmpty()){
count++;
int noPreNode = queue.poll();
for(int i = 0;i < n;i++){
if(graph[i][noPreNode]==1){
//graph[i][noPreNode] = 0;
if(--degree[i]==0)
queue.offer(i);
}
}
}
return count == n;
}
提交之后,最后一个测试用例超时,是一个n=2000的案例,也就是graph[2000][2000];想不明白,看别人的代码,发现唯一的区别就是我用的graph[ready][pre];ready表示节点,pre表示连向它的节点,即先修课程;而别人用的graph[pre][ready];为什么这点区别我的就过不了了呢?查询后发现java二维数组的顺序是行优先的,而我在最后的度为0 的操作中遍历数组的ready,我的ready在不同的行上,相当于遍历了每一行的某个固定列的元素,可想而知操作要多了很多。
for(int i = 0;i < n;i++){
if(graph[i][noPreNode]==1){
//graph[i][noPreNode] = 0;
if(--degree[i]==0)
queue.offer(i);
}
}
关于java二维数组内存操作http://www.cnblogs.com/nonghu/p/6328530.html该博客有介绍http://blog.csdn.net/silentbalanceyh/article/details/42643747