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 numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
One way to solve this problem is to use topological sorting, which orders the courses such that for every pair of courses (ai, bi) where bi is a prerequisite of ai, bi comes before ai 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 O(V + E), where V is the number of courses and E is the number of prerequisites, and a space complexity of O(V + E), since it uses an adjacency list and an in-degree array.