-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse_Schedule.cpp
More file actions
72 lines (58 loc) · 1.73 KB
/
Course_Schedule.cpp
File metadata and controls
72 lines (58 loc) · 1.73 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 adity on 29-11-2024.
//
#include "Course_Schedule.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
class Solution {
public:
bool topologicalSortCheck(unordered_map<int, vector<int>> adj, int n, vector<int>& indegree) {
queue<int> que;
int count = 0;
for (int i = 0; i < n; i++) {
if (indegree[i] == 0) {
count++;
que.push(i);
}
}
while (!que.empty()) {
int u = que.front();
que.pop();
for (int& v : adj[u]) {
indegree[v]--;
if (indegree[v] == 0) {
count++;
que.push(v);
}
}
}
return count == n; // True if all nodes can be visited
}
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
unordered_map<int, vector<int>> adj; // Adjacency list for graph
vector<int> indegree(numCourses, 0); // Indegree array for Kahn's algorithm
for (auto& vec : prerequisites) {
int a = vec[0];
int b = vec[1];
adj[b].push_back(a); // b --> a
indegree[a]++;
}
return topologicalSortCheck(adj, numCourses, indegree);
}
};
int main() {
Solution solution;
int numCourses = 4; // Example number of courses
vector<vector<int>> prerequisites = {
{1, 0}, {2, 1}, {3, 2} // Example prerequisites
};
if (solution.canFinish(numCourses, prerequisites)) {
cout << "All courses can be finished." << endl;
} else {
cout << "Not all courses can be finished due to a cycle." << endl;
}
return 0;
}