问题引入
leetcode题目:
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?
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的节点,判断还有无剩下的节点
代码:
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
如果数组很大的话应该是行优先快吧,因为数组在内存中是按行优先存储的,在虚存环境下,如果整个数组没有在内存中的话可以比列优先减少内存换进换出的次数(具体术语是什么我也记不清楚了)。就算整个数组都在内存中,列优先访问a[i][j]还得计算一次乘法,行优先只需加一就可以了,这个可以忽略