207. Course Schedule(Graph; BFS)

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]
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.

Hints:
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.

思路:拓扑排序。

拓扑排序的含义是:对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。

拓扑排序的方法是:用一个队列存入度为0的节点,依次出队,将与出队节点相连的节点的入度减1,如果入度减为0,将其放入队列中,直到队列为空。如里最后还有入度不为0的节点的话,说明有环(有环的情况必定有节点入度无法减到0,比如环刚开始处的那个节点),否则无环。

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> graph(numCourses, vector<int>(0));
        vector<int> inDegree(numCourses,0);
        queue<int> que;
        int cur;
        
        for(auto p: prerequisites){
            graph[p.first].push_back(p.second);
            inDegree[p.second]++;
        }
        
        for(int i = 0; i < numCourses; i++){ //find the first point
            if(inDegree[i]==0) que.push(i);
        }
        
        while(!que.empty()){ //BFS by using queue; stack can be used to realize DFS
            cur = que.front();
            que.pop();
            for(auto p: graph[cur]){
                inDegree[p]--;
                if(inDegree[p]==0) que.push(p);
            }
        }
        
        for(int i = 0; i < numCourses; i++){
            if(inDegree[i]!=0) return false;
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/qionglouyuyu/p/5092167.html