forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJudge_Circle.cpp
73 lines (60 loc) · 1.3 KB
/
Judge_Circle.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
int numNodes;
int visited[numNodes];
vector<vector<int>> next;
main()
{
// prepare next; // next[i][j]: there is a directional path i->j
// dfs 判断有环
for (int i=0; i<numNodes; i++)
{
if (dfs(i)==false) return false;
}
return true;
// bfs 判断有环
return bfs();
}
bool dfs(int cur)
{
if (visited[cur]==1) return true;
visited[cur] = 2;
for (int next: next[cur])
{
if (visited[next]==1) continue;
if (visited[next]==2) return false;
if (dfs(next)==false) return false;
}
visited[cur] = 1;
return true;
}
bool bfs()
{
queue<int>q;
int count = 0;
vector<int>InDegree(numNodes,0);
for (int i=0; i<numNodes; i++)
for (int j: next[i])
InDegree[j]++;
for (int i=0; i<numNodes; i++)
{
if (InDegree[i]==0)
{
q.push(i);
count++;
}
}
while (!q.empty())
{
int curCourse = q.front();
q.pop();
for (auto child: next[curCourse])
{
InDegree[child]--;
if (InDegree[child]==0)
{
q.push(child);
count++;
}
}
}
return count==numNodes;
}