Leetcode 207. Course Schedule

本文探讨了如何判断在存在先修课程约束的情况下是否能完成所有课程的问题。通过使用拓扑排序的方法,文章提供了一种有效解决方案,并附带了一个不适用但用于回忆Floyd算法实现的示例。

题目:

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.

思路:拓扑排序,用floyd尝试了一下,主要是回忆一下怎么写。复杂度太高跑不完。最后用拓扑可以。
//floyd
class Solution {       
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> map(numCourses,vector<int>(numCourses,10000)); //10000是设置的一个最大边长值
        for(int i = 0; i < prerequisites.size(); i++){
            map[prerequisites[i].first][prerequisites[i].second] = 1;
        }
        vector<vector<int>> d = map;
        int n = numCourses;
        vector<vector<int>> tmp = d;
        for(int k = 0; k < n; k++){  
            vector<vector<int>> tmp = d;
             for(int i = 0; i < n; i++)
                for(int j = 0; j < n;j++)
                    tmp[i][j] = min(d[i][j],d[i][k]+d[k][j]);
             d = tmp;
        } 
        
        for(int i = 0; i < n;i++){
            for(int j = i+1; j < n; j++){
                if(d[i][j] != 10000&&d[j][i] !=10000) return false;
            }
        }
        return true;
    }
};
拓扑排序;

class Solution {  
public:  
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {  
        if(numCourses == 0) return false;  
        vector<int> indegree(numCourses, 0);  
        unordered_map<int, multiset<int>> hash;  
        for(auto val: prerequisites)  
        {  
            indegree[val.first]++;  
            hash[val.second].insert(val.first);  
        }  
        for(int i = 0, j; i < numCourses; i++)  
        {  
            for(j = 0; j < numCourses; j++)  
                if(indegree[j]==0) break;  
            if(j==numCourses) return false;  
            indegree[j]--;  
            for(auto val: hash[j]) indegree[val]--;  
        }  
        return true;  
    }  
}; 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值