forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
74 lines (63 loc) · 1.28 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Graph
{
int V;
list<int> *adj;
queue<int> q;
int* indegree;
public:
Graph(int V);
~Graph();
void addEdge(int v, int w);
bool topological_sort();
};
/************************类定义************************/
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
indegree = new int[V];
for(int i=0; i<V; ++i)
indegree[i] = 0;
}
Graph::~Graph()
{
delete [] adj;
delete [] indegree;
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
++indegree[w];
}
bool Graph::topological_sort()
{
for(int i=0; i<V; ++i)
if(indegree[i] == 0)
q.push(i);
int count = 0;
while(!q.empty())
{
int v = q.front();
q.pop();
++count;
list<int>::iterator beg = adj[v].begin();
for( ; beg!=adj[v].end(); ++beg)
if(!(--indegree[*beg]))
q.push(*beg);
}
if(count < V)
return false;
else
return true;
}
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int> >& prerequisites)
{
Graph g(numCourses);
for(int i=0; i<prerequisites.size(); ++i)
g.addEdge(prerequisites[i][1], prerequisites[i][0]);
return g.topological_sort();
}
};