LeetCode 207. Course Schedule
原题链接
中等
作者:
JasonSun
,
2020-08-29 04:04:24
,
所有人可见
,
阅读 367
Topological Sort (DFS)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
enum status_t {untouched, explore, done};
const auto G = [&](std::vector<std::vector<int>> self = {}) {
self.resize(numCourses);
for (const auto& e : prerequisites) {
const auto [u, v] = std::pair{e[0], e[1]};
self[v].emplace_back(u);
}
return self;
}();
const auto solution = [&](bool acc = true) {
auto status = std::vector<status_t>(numCourses, untouched);
std::function<void(int)> fold = [&](int u) mutable {
if (status[u] == explore) {
acc = false;
return;
}
else {
std::exchange(status[u], explore);
for (const auto v : G[u]) {
if (status[v] != done) {
fold(v);
}
}
std::exchange(status[u], done);
}
};
for (int i = 0; i < numCourses and acc == true; ++i) {
if (status[i] == untouched) {
fold(i);
}
}
return acc;
}();
return solution;
}
};
Topological Sort (BFS)
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
const auto G = [&](std::vector<std::vector<int>> self = {}) {
self.resize(numCourses);
for (const auto e : prerequisites) {
const auto [u, v] = std::pair{e[0], e[1]};
self[v].emplace_back(u);
}
return self;
}();
const auto indegree = [&](std::vector<int> self = {}) {
self.resize(numCourses);
for (int u = 0; u < numCourses; ++u) {
for (const auto v : G[u]) {
self[v]++;
}
}
return self;
}();
const auto solution = [&](bool acc = true) {
struct state_t {
mutable std::deque<int> Q;
};
const auto ST = state_t {
.Q = [&](std::deque<int> self = {}) {
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) {
self.emplace_back(i);
}
}
return self;
}()
};
std::function<void(void)> bfs = [&, indegree = indegree, cnt = std::size(ST.Q)]() mutable {
auto & Q = ST.Q;
if (std::empty(Q)) {
if (cnt != numCourses) {
std::exchange(acc, false);
}
return;
}
else {
const auto u = Q.front();
Q.pop_front();
for (const auto v : G[u]) {
if (--indegree[v] == 0) {
++cnt;
Q.emplace_back(v);
}
}
bfs();
}
};
return bfs(), acc;
}();
return solution;
}
};