题目
思路
还是拓扑排序的思路。需要注意的是,这题的量变大了,会有2000门或以上的课,因此用malloc动态分配数组。
其实C真的挺好玩。
代码
int * findOrder(int numCourses, int ** prerequisites, int prerequisitesRowSize, int prerequisitesColSize, int * returnSize) {
int * Indegrees;
int * Outdegrees;
int ** IsConnect;
Indegrees = (int*)malloc(sizeof(int) * numCourses);
Outdegrees = (int*)malloc(sizeof(int) * numCourses);
IsConnect = (int**)malloc(sizeof(int*) * numCourses);
for (int i = 0; i < numCourses; i++) Indegrees[i] = Outdegrees[i] = 0;
for (int i = 0; i < prerequisitesRowSize; i++) {
Indegrees[prerequisites[i][0]]++;
Outdegrees[prerequisites[i][1]]++;
}
for (int i = 0; i < numCourses; i++) {
IsConnect[i] = (int*)malloc(sizeof(int) * (Outdegrees[i] + 1));
IsConnect[i][0] = 0;
}
for (int i = 0; i < prerequisitesRowSize; i++) {
IsConnect[prerequisites[i][1]][++IsConnect[prerequisites[i][1]][0]] = prerequisites[i][0];
}
int * Q = (int*)malloc(sizeof(int) * numCourses);
int head = 0, tail = 0, Ans = 0;
for (int i = 0; i < numCourses; i++) {
if (Indegrees[i] == 0) {
Q[tail++] = i;
Ans++;
}
}
int * Order = (int*)malloc(sizeof(int) * numCourses);
int k = 0;
while (head < tail) {
for (int i = 1; i <= IsConnect[Q[head]][0]; i++) {
Indegrees[IsConnect[Q[head]][i]]--;
if (Indegrees[IsConnect[Q[head]][i]] == 0) {
Q[tail++] = IsConnect[Q[head]][i];
Ans++;
}
}
Order[k++] = Q[head];
head++;
}
free(Indegrees);
free(Outdegrees);
for (int i = 0; i < numCourses; i++) {
free(IsConnect[i]);
}
free(IsConnect);
free(Q);
if (Ans == numCourses) {
*returnSize = numCourses;
return Order;
}
else {
free(Order);
*returnSize = 0;
return NULL;
}
}
原文地址:http://blog.csdn.net/u012925008/article/details/45720467