Skip to content

Commit dfa8012

Browse files
authored
Merge branch 'main' into main
2 parents 32b64a8 + 97e83c8 commit dfa8012

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

206.Course Schedule.cpp

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// 🧠 Approach
2+
3+
// This problem can be modeled as a Directed Graph Cycle Detection problem.
4+
// Each course is represented as a node, and a directed edge b → a means you must take course b before course a.
5+
6+
// To determine if all courses can be finished, we must ensure no cycle exists in this graph.
7+
// We use Kahn’s Algorithm (Topological Sorting using BFS) to detect cycles.
8+
9+
// 🚀 Algorithm Steps
10+
11+
// Build the Graph:
12+
13+
// - Create an adjacency list adj where adj[b] contains all courses that depend on b.
14+
// - Maintain an array inDeg to store the number of prerequisites (incoming edges) for each course.
15+
16+
// Find Starting Nodes:
17+
18+
// - Push all nodes with inDeg[i] == 0 (no prerequisites) into a queue — these can be taken first.
19+
// - Topological Sorting using BFS:
20+
// - While the queue isn’t empty:
21+
// - Pop a node x (a course that can be completed now).
22+
// - Increment a counter c for completed courses.
23+
// - For each neighbor adj[x][i], reduce its inDeg by 1 (as its prerequisite x is now done).
24+
// - If any neighbor’s inDeg becomes 0, push it into the queue.
25+
26+
// Check Completion:
27+
28+
// - If all courses are processed (c == V), return true.
29+
// - Otherwise, there’s a cycle → some courses depend on each other, so return false.
30+
31+
32+
// Solution in CPP:
33+
34+
class Solution {
35+
public:
36+
bool canFinish(int V, vector<vector<int>>& prerequisites) {
37+
vector<vector<int>> adj(V);
38+
vector<int> inDeg(V);
39+
for (int i = 0; i < prerequisites.size(); i++) {
40+
int a = prerequisites[i][0];
41+
int b = prerequisites[i][1];
42+
43+
adj[b].push_back(a);
44+
inDeg[a]++;
45+
}
46+
vector<int> vis(V);
47+
queue<int> q;
48+
49+
for (int i = 0; i < V; i++) {
50+
if (inDeg[i] == 0)
51+
q.push(i);
52+
}
53+
int c = 0;
54+
while (!q.empty()) {
55+
int x = q.front();
56+
q.pop();
57+
c++;
58+
59+
for (int i = 0; i < adj[x].size(); i++) {
60+
inDeg[adj[x][i]]--;
61+
if (inDeg[adj[x][i]] == 0)
62+
q.push(adj[x][i]);
63+
}
64+
}
65+
return c == V;
66+
}
67+
};

0 commit comments

Comments
 (0)