-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
49 lines (42 loc) · 1.04 KB
/
Copy pathsolution.cpp
File metadata and controls
49 lines (42 loc) · 1.04 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
class Solution
{
public:
bool canFinish(int n, vector<vector<int>> &prerequisites)
{
vector<vector<int>> adj(n);
vector<int> indegree(n, 0);
// Build graph
for (auto &p : prerequisites)
{
adj[p[1]].push_back(p[0]);
indegree[p[0]]++;
}
queue<int> q;
// Push nodes with 0 indegree
for (int i = 0; i < n; i++)
{
if (indegree[i] == 0)
{
q.push(i);
}
}
int count = 0;
// BFS (Topological Sort)
while (!q.empty())
{
int node = q.front();
q.pop();
count++;
for (int neighbor : adj[node])
{
indegree[neighbor]--;
if (indegree[neighbor] == 0)
{
q.push(neighbor);
}
}
}
// If all nodes processed, no cycle
return count == n;
}
};