xinyu04

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

LeetCode 207 Course Schedule 拓扑排序BFS

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 course 0 you have to first take course 1.
Return true if you can finish all courses. Otherwise, return false.

Solution

拓扑排序的模板题。每次建边从 biai,然后 ai 的度数 +1。每次取出度数为 0 的点加入队列,然后将删除这些点相连的边:即将 ai 的度数 1,再将度数为 0 的点加入队列直到没有点满足条件。如果最后符合条件点数 = numCourses,则为true;否则为false

点击查看代码
class Solution {
private:
vector<int> vec[2004];
int deg[2002];
vector<int> ans;
public:
bool canFinish(int numCourses, vector<vector<int>>& preq) {
for(int i=0;i<preq.size();i++){
vec[preq[i][1]].push_back(preq[i][0]);
deg[preq[i][0]]+=1;
}
for(int i=0;i<numCourses;i++){
if(deg[i]==0)ans.push_back(i);
}
for(int i=0;i<ans.size();i++){
int N = vec[ans[i]].size();
for(int j=0;j<N;j++){
deg[vec[ans[i]][j]]-=1;
if(deg[vec[ans[i]][j]]==0)ans.push_back(vec[ans[i]][j]);
}
}
if(ans.size()==numCourses)return true;
return false;
}
};

posted on   Blackzxy  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示