The problem of Course Schedule on LeetCode is to determine if it is possible to finish all courses given the prerequisites. There are a total of courses you have to take, labeled from to . You are given an array where indicates that you must take course first if you want to take course .
One way to solve this problem is to use topological sorting, which orders the courses such that for every pair of courses where is a prerequisite of , comes before in the ordering. If such an ordering exists, then it is possible to finish all courses. Otherwise, there is a cycle in the graph of courses and prerequisites, and it is impossible to finish all courses.
Hereβs C++ implementation:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
bool canFinish(int numCourses, vector<vector<int>> &prerequisites) {
vector<int> inDegree(numCourses, 0);
vector<vector<int>> graph(numCourses);
// Build the graph and calculate in-degrees
for (const vector<int> &prereq : prerequisites) {
graph[prereq[1]].push_back(prereq[0]);
inDegree[prereq[0]]++;
}
// Initialize a queue for topological sorting
queue<int> q;
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] == 0) {
q.push(i);
}
}
// Perform topological sorting
while (!q.empty()) {
int course = q.front();
q.pop();
numCourses--;
for (int neighbor : graph[course]) {
if (--inDegree[neighbor] == 0) {
q.push(neighbor);
}
}
}
return numCourses == 0;
}
int main() {
int numCourses = 2;
vector<vector<int>> prerequisites = {{1, 0}};
if (canFinish(numCourses, prerequisites)) {
cout << "You can finish all courses!" << endl;
} else {
cout << "You cannot finish all courses!" << endl;
}
return 0;
}
Here are the key steps in the solution:
This code has a time complexity of , where is the number of courses and is the number of prerequisites, and a space complexity of , since it uses an adjacency list and an in-degree array.