【leetcode】207. 课程表
int** edges;
int* edgeColSize;
int* visited;
bool valid;
void dfs(int u) {
visited[u] = 1;
for (int i = 0; i < edgeColSize[u]; ++i) {
if (visited[edges[u][i]] == 0) {
dfs(edges[u][i]);
if (!valid) {
return;
}
}
else if (visited[edges[u][i]] == 1) {
valid = false;
return;
}
}
visited[u] = 2;
}
bool canFinish(int numCourses, int** prerequisites, int prerequisitesSize, int* prerequisitesColSize) {
valid = true;
edges = (int**)malloc(sizeof(int*)* numCourses);
for (int i = 0; i < numCourses; i++) {
edges[i] = (int*)malloc(0);
}
edgeColSize = (int*)calloc(sizeof(int), numCourses);
visited = (int*)calloc(sizeof(int), numCourses);
for (int i = 0; i < prerequisitesSize; ++i) {
int a = prerequisites[i][1], b = prerequisites[i][0];
edgeColSize[a]++;
edges[a] = (int*)realloc(edges[a], sizeof(int)* edgeColSize[a]);
edges[a][edgeColSize[a] - 1] = b;
}
for (int i = 0; i < numCourses && valid; ++i) {
if (!visited[i]) {
dfs(i);
}
}
return valid;
}
bool canFinish(int numCourses, int** prerequisites, int prerequisitesSize, int* prerequisitesColSize) {
int** edges = (int**)malloc(sizeof(int*) * numCourses);
for (int i = 0; i < numCourses; i++) {
edges[i] = (int*)malloc(0);
}
int edgeColSize[numCourses];
memset(edgeColSize, 0, sizeof(edgeColSize));
int indeg[numCourses];
memset(indeg, 0, sizeof(indeg));
for (int i = 0; i < prerequisitesSize; ++i) {
int a = prerequisites[i][1], b = prerequisites[i][0];
edgeColSize[a]++;
edges[a] = (int*)realloc(edges[a], sizeof(int) * edgeColSize[a]);
edges[a][edgeColSize[a] - 1] = b;
++indeg[b];
}
int q[numCourses];
int l = 0, r = -1;
for (int i = 0; i < numCourses; ++i) {
if (indeg[i] == 0) {
q[++r] = i;
}
}
int visited = 0;
while (l <= r) {
++visited;
int u = q[l++];
for (int i = 0; i < edgeColSize[u]; ++i) {
--indeg[edges[u][i]];
if (indeg[edges[u][i]] == 0) {
q[++r] = edges[u][i];
}
}
}
for (int i = 0; i < numCourses; i++) {
free(edges[i]);
}
free(edges);
return visited == numCourses;
}