leetcode 207. Course Schedule

本文介绍了一种算法,用于判断在存在先修课程约束的情况下,是否有可能完成所有课程。通过使用图论中的拓扑排序思想,文章详细解释了如何检测课程依赖图中是否存在环,进而确定能否完成所有课程。
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.

   这个题的关键在于 就是图的思想,有没有环的存在
   方法是使用拓扑排序思想,找入度为0的点,然后删除这个点以及出边,重复这个过程,如果找不到入度为0得点就说明有环!
   
   使用indegree数组来存入度。


class Solution {
public:
    int findpoint(vector<int> &indegree, int num)//找入度为0的点
    {
        int flag = 0;
        for (int i = 0; i < num; i++)
        {
            if(indegree[i] == 0)
            {  
                indegree[i]--;
                return i;
            }
        }
        return -1;
    }
    
    bool canFinish(int num, vector<pair<int, int>>& prer) 
    {
        //形成邻接矩阵
        vector<int> indegree(num, 0);
        vector<vector<int>> p(num, indegree);
       
        for (auto it : prer)
        {
            p[it.first][it.second] = 1;
            indegree[it.second]++;
        }
       
        //就是看一个有向图是否形成环,return 0。
        int taken = 0;
        while (taken != num)
        {
            int k = findpoint(indegree, num);
            if(k == -1)    //没有入度为0的点
                return false;
            for (int i = 0; i < num; i++)        
            {  
                if( p[k][i] == 1)
                    indegree[i]--;
            }
            taken++;    
        }
        return true;   
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值