Leetcode 18 Course Schedule

来源:互联网 发布:网络机房存储设备 编辑:程序博客网 时间:2024/06/07 02:17

1、题目描述
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.
题意大概是给定一个课程总数和多个二元组,如第一个例子所示,二元组[1,0]表示你必须已经完成课程0的学习才能修课程1,求在给定的二元组限制条件下,能否顺利修完所有课程。
2、解题思路
该题目等价于由课程构成顶点集,二元组构成顶点之间的边,构成一个有向图,求解该题等于求解构造的这个有向图中是否具有环的存在。
解题过程首先需要构造一个有向图,利用函数struct_dg实现,存储每个节点对应的直系子节点。
然后利用BFS搜索方法进行判断是否有环的存在,实现统计每个节点的入度。如果存在入度为节点个数的节点,肯定存在环,返回false,否则依次删除入度为0的节点,然后更新各个节点的入度数,直至最后所有入度均为-1
3、实现代码

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {       vector<vector<int>> dg=struct_dg(numCourses, prerequisites);//construct the corrosponding directed graph       vector<int> indegree=comp_indegree(numCourses,dg);       for(int i=0;i<numCourses;i++){            int j=0;            for(;j<numCourses;j++)                if(indegree[j]==0) break;            if(j==numCourses)  return false;            //delete the node without pre-nodes and then judge that there are cycles between the rest of the dg utilizing the loop about i            indegree[j]=-1;            for(auto k:dg[j]) indegree[k]--;       }       return true;    }    vector<vector<int>> struct_dg(int &num,vector<pair<int, int>>& prerequisites){        vector<vector<int>> graph(num);        for(auto i:prerequisites){           graph[i.second].push_back(i.first);        }        return graph;        //the dg contain post node set of the i-th node     }    vector<int> comp_indegree(int num, vector<vector<int>> graph){        vector<int> indegree(num,0);        for(auto i:graph){            for(auto j:i) indegree[j]++;        }        return indegree;        //compute the number of pre-node of every node    }};

4、实验结果
Submission Details
37 / 37 test cases passed.
Status: Accepted
Runtime: 26 ms
Submitted: 1 minute ago
Accepted Solutions Runtime Distribution