Description
There are a total of n courses you have to take, labeled from 0 to n - 1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
my program
思路:拓扑排序
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> tmp(numCourses, 0);
multimap<int, int> mp;
for (int i = 0; i < prerequisites.size(); i++) {
tmp[prerequisites[i].second]++;
mp.insert(make_pair(prerequisites[i].first, prerequisites[i].second));
}
while (1) {
auto it = find(tmp.begin(), tmp.end(), 0);
if (it == tmp.end())
break;
int index = it - tmp.begin();
tmp[index] = -1;
auto beg = mp.lower_bound(index);
auto end = mp.upper_bound(index);
for (;beg != end; beg++) {
tmp[beg->second]--;
}
}
for (auto i : tmp) {
if (i != -1) {
return false;
}
}
return true;
}
};
Submission Details
37 / 37 test cases passed.
Status: Accepted
Runtime: 33 ms
other program
有向无环图的判断可采用dfs或bfs,至于生成图的形式可以是邻接矩阵,也可以是邻接表。为了减小时间复杂度,以下采用邻接表的方法。
以空间换时间
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> mp(numCourses, vector<int>());
for (int i = 0; i < prerequisites.size(); i++) {
mp[prerequisites[i].first].push_back(prerequisites[i].second);
}
vector<bool> isVisited(numCourses, false);
for (int i = 0; i < numCourses; i++) {
if (!isVisited[i]) {
vector<bool> onStack(numCourses, false);
if (hasCycle(mp, i, isVisited, onStack))
return false;
}
}
return true;
}
bool hasCycle(vector<vector<int>>& mp, int i, vector<bool>& isVisited, vector<bool>& onStack) {
isVisited[i] = true;
onStack[i] = true;
for (auto k : mp[i]) {
if (onStack[k])
return true;
else if (hasCycle(mp, k, isVisited, onStack))
return true;
}
onStack[i] = false;
return false;
}
};
Submission Details
37 / 37 test cases passed.
Status: Accepted
Runtime: 22 ms