2023-07-13 Daily Challenge
Today I have done leetcode's July LeetCoding Challenge with cpp
.
July LeetCoding Challenge 13
Description
Course Schedule
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
.
- For example, the pair
[0, 1]
, indicates that to take course0
you have to first take course1
.
Return true
if you can finish all courses. Otherwise, return false
.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]] Output: true Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]] Output: false Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
- All the pairs prerequisites[i] are unique.
Solution
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<int> degree(numCourses);
vector<vector<int>> edges(numCourses);
for(auto &edge : prerequisites) {
edges[edge[0]].push_back(edge[1]);
degree[edge[1]] += 1;
}
queue<int> q;
int answer = 0;
for(int i = 0; i < numCourses; ++i) {
if(!degree[i]) {
answer += 1;
q.push(i);
}
}
while(q.size()) {
int cur = q.front();
q.pop();
for(auto nxt : edges[cur]) {
degree[nxt] -= 1;
if(!degree[nxt]) {
answer += 1;
q.push(nxt);
}
}
}
return answer == numCourses;
}
};
// Accepted
// 52/52 cases passed (25 ms)
// Your runtime beats 62.83 % of cpp submissions
// Your memory usage beats 83.94 % of cpp submissions (13.2 MB)