Repository navigation
Expand file tree
/
Copy path207.cpp
More file actions
72 lines (71 loc) · 1.96 KB
/
Copy path207.cpp
File metadata and controls
72 lines (71 loc) · 1.96 KB
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
//
// Created by arsen on 31.10.2025.
//
#include <vector>
class Solution {
public:
bool dfs(std::vector<std::vector<int>>& nums, int v, std::vector<int>& visited, std::vector<int>& order) {
visited[v] = 1;
order[v] = 1;
for (int to : nums[v]) {
if (!visited[to]) {
if (dfs(nums, to, visited, order)) {
return true;
}
} else if (order[to]) {
return true;
}
}
order[v] = false;
return false;
}
bool canFinish(int numCourses, std::vector<std::vector<int>>& prerequisites) {
std::vector<std::vector<int>> adj(numCourses);
for (const auto& pre : prerequisites) {
adj[pre[1]].push_back(pre[0]);
}
std::vector<int> order(numCourses);
std::vector<int> visited(numCourses);
for (int i = 0; i < numCourses; i++) {
if (!visited[i]) {
if (dfs(adj, i, visited, order)) {
return false;
}
}
}
return true;
}
};
// Через алгоритм Кана:
/*
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> adj(numCourses);
vector<int> indegree(numCourses, 0);
for (const auto& pre : prerequisites) {
adj[pre[1]].push_back(pre[0]);
indegree[pre[0]]++;
}
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (indegree[i] == 0) {
q.push(i);
}
}
int count = 0;
while (!q.empty()) {
int node = q.front();
q.pop();
count++;
for (int next : adj[node]) {
indegree[next]--;
if (indegree[next] == 0) {
q.push(next);
}
}
}
return count == numCourses;
}
};
*/