Leetcode 18 Course Schedule

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值