-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path207.cpp
101 lines (90 loc) · 2.63 KB
/
207.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <bits/stdc++.h>
#include <gtest/gtest.h>
using namespace std;
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>> &prerequisites)
{
vector<vector<int>> neighbors(numCourses);
vector<int> inDegree(numCourses, 0);
for (auto &pre : prerequisites) {
neighbors[pre[1]].push_back(pre[0]);
inDegree[pre[0]]++;
}
queue<int> zeroDegree;
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] == 0) {
zeroDegree.push(i);
}
}
int visitedNodes = 0;
while (!zeroDegree.empty()) {
int node = zeroDegree.front();
zeroDegree.pop();
visitedNodes++;
for (int neighbor : neighbors[node]) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
zeroDegree.push(neighbor);
}
}
}
return visitedNodes == numCourses;
}
};
TEST(CanFinishTest, NoPrerequisites)
{
Solution solution;
int numCourses = 3;
vector<vector<int>> prerequisites = {};
EXPECT_TRUE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, SinglePrerequisite)
{
Solution solution;
int numCourses = 2;
vector<vector<int>> prerequisites = {{1, 0}};
EXPECT_TRUE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, MultiplePrerequisitesPossible)
{
Solution solution;
int numCourses = 4;
vector<vector<int>> prerequisites = {{1, 0}, {2, 1}, {3, 2}};
EXPECT_TRUE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, CircularDependencyImpossible)
{
Solution solution;
int numCourses = 2;
vector<vector<int>> prerequisites = {{1, 0}, {0, 1}};
EXPECT_FALSE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, ComplexGraphWithCycle)
{
Solution solution;
int numCourses = 5;
vector<vector<int>> prerequisites = {
{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 1}};
EXPECT_FALSE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, LargeGraphNoCycle)
{
Solution solution;
int numCourses = 6;
vector<vector<int>> prerequisites = {
{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}};
EXPECT_TRUE(solution.canFinish(numCourses, prerequisites));
}
TEST(CanFinishTest, IsolatedCourses)
{
Solution solution;
int numCourses = 3;
vector<vector<int>> prerequisites = {{1, 0}};
EXPECT_TRUE(solution.canFinish(numCourses, prerequisites));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}