题目
思路
明显的拓扑排序。
这里用的C写,用malloc动态分配内存给二维数组挺烦的,当做锻炼吧。
代码
bool canFinish(int numCourses, int** prerequisites, int prerequisitesRowSize, int prerequisitesColSize) {
int * Indegrees;
bool ** IsConnect;
Indegrees = (int*)malloc(sizeof(int) * numCourses);
IsConnect = (bool**)malloc(sizeof(bool*) * numCourses);
for (int i = 0; i < numCourses; i++) {
IsConnect[i] = (bool*)malloc(sizeof(bool) * numCourses);
}
//memset(Indegrees, 0, sizeof(Indegrees));
//memset(IsConnect, false, sizeof(IsConnect)); something wrong here
for (int i = 0; i < numCourses; i++) Indegrees[i] = 0;
for (int i = 0; i < numCourses; i++) for (int j = 0; j < numCourses; j++) IsConnect[i][j] = false;
for (int i = 0; i < prerequisitesRowSize; i++) {
int To = prerequisites[i][0];
for (int j = 1; j < prerequisitesColSize; j++) {
if (0 <= prerequisites[i][j] && prerequisites[i][j] < numCourses && !IsConnect[prerequisites[i][j]][To]) {
IsConnect[prerequisites[i][j]][To] = true;
Indegrees[To]++;
}
}
}
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++;
}
}
while (head < tail) {
for (int i = 0; i < numCourses; i++) {
if (IsConnect[Q[head]][i]) {
IsConnect[Q[head]][i] = false;
Indegrees[i]--;
if (Indegrees[i] == 0) {
Q[tail++] = i;
Ans++;
}
}
}
head++;
}
free(Indegrees);
for (int i = 0; i < numCourses; i++) {
free(IsConnect[i]);
}
free(Q);
return Ans == numCourses;
}
原文地址:http://blog.csdn.net/u012925008/article/details/45560881