zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    Windows中目录及文件路径太长无法删除的解决方法
    html5--移动端视频video的android兼容,去除播放控件、全屏等
    npm scripts 使用指南
    如何在 React Native 中写一个自定义模块
    流媒体测试笔记记录之————解决问题video.js 播放m3u8格式的文件,根据官方的文档添加videojs-contrib-hls也不行的原因解决了
    React.js 小书
    React.js 应用 UI 框架
    npm配置文件
    Linux 普通进程 后台进程 守护进程
    Linux下passwd和shadow文件内容详解
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5092167.html
Copyright © 2011-2022 走看看