#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
struct ArchNode {
int idx;
struct ArchNode* next;
ArchNode(int i): idx(i), next(nullptr) {}
};
struct VertexNode {
struct ArchNode* first = nullptr;
struct ArchNode* tail = nullptr;
};
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
const int n = numCourses;
int in_degree[n];
fill_n(in_degree, n, 0);
struct VertexNode vertexes[n];
const unsigned int arch_size = prerequisites.size();
struct ArchNode* arches[arch_size];
vector<int> result;
int arch_count = 0;
for (auto edge : prerequisites) {
int idx = edge[0], st = edge[1];
in_degree[idx]++;
ArchNode* p = new ArchNode(idx);
arches[arch_count++] = p;
if (vertexes[st].first == nullptr) {
vertexes[st].first = p;
vertexes[st].tail = p;
} else {
vertexes[st].tail->next = p;
vertexes[st].tail = vertexes[st].tail->next;
}
}
int count = numCourses;
while (count--) {
int i = find_indegree_0_node(in_degree, n);
if (i == -1){
cout << "can't find node whose in-degree is 0" << endl;
return false;
}
ArchNode* q = vertexes[i].first;
while (q) {
int j = q->idx;
in_degree[j]--;
q = q->next;
}
in_degree[i] = -1;
result.push_back(i);
}
cout << "count=" << count << endl;
cout << "topologic list=";
for(auto r : result)
cout << r << " ";
cout << endl;
clearVertexNodes(arches, arch_count);
return true;
}
private:
int find_indegree_0_node(int* in_degree, const int size) {
for (int i = 0; i < size; ++i) {
if (in_degree[i] == 0)
return i;
}
return -1;
}
void clearVertexNodes(ArchNode** arches, int size) {
for (int j = 0; j < size; ++j) {
delete arches[j];
}
}
};
- 第一次提交就通过了;
- 删除了创建的边集节点避免内存泄漏; 但是从提交结果来看并没有省多少内存;
- arch_count必须是unsigned, 避免负0出现在数组定义;