xinyu04

导航

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

拓扑排序的模板题。每次建边从 \(b_i \rightarrow a_i\),然后 \(a_i\) 的度数 \(+1\)。每次取出度数为 \(0\) 的点加入队列,然后将删除这些点相连的边:即将 \(a_i\) 的度数 \(-1\),再将度数为 \(0\) 的点加入队列直到没有点满足条件。如果最后符合条件点数 \(=\ \text{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 2022-05-18 03:00  Blackzxy  阅读(18)  评论(0编辑  收藏  举报