No210. Course Schedule II

本文针对课程排序问题,提出一种基于深度优先搜索(DFS)的方法来确定完成所有课程所需的正确顺序。通过对每门课程及其先修课程进行分析,利用图论中的拓扑排序原理,文章详细阐述了解决方案的具体步骤,并提供了完整的代码实现。

一、题目描述

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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

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 the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

二、解题思路

本题的解题思路来自于上一篇博客(即No.207),在利用DFS计算出图中每个节点的pre和post后,按照post值的大小顺序排列,则为最终的拓扑顺序。代码之所以较长是因为要考虑很多特殊情况。1、当限制条件为空时,随便排序。2、当图中有环时,要返回空。3、对post排序不能只对[numCourses+1,2*numCourses]的数排序,因为有可能存在由1指向0的边:1—>0;但是标注pre和post时先访问了节点0,。其中第三点是在本道题目的测试用例中才发现的,忽然意识到在做N0.207时没有考虑到这种情况,但是当时也没有相应的测试用例报错,所以顺利通过了。

三、代码实现

class Solution {
public:
    int count=0;
    vector<int> findOrder(int numCourses, vector<pair<int,int>>& prerequisites) {
        vector<int> result;
        if(prerequisites.size()==0){
            for(int i=0;i<numCourses;i++){
                result.push_back(i);
            }
            return result;
        }
        
        vector<set<int>> graph(numCourses);
        for(auto pr:prerequisites){
            graph[pr.first].insert(pr.second);
        }
        
        vector<pair<int,int>> point(numCourses,make_pair(0,0));
        for(int i=0;i<numCourses;i++)
            dfs(graph,point,i);
            
        for(int v=0;v<numCourses;v++)  
            for(int u:graph[v])  
                if(point[v].first>point[u].first&&point[v].second<point[u].second)
                    return result;
                
        for(int i=1;i<=2*numCourses;i++){
            for(int j=0;j<numCourses;j++){
                if(point[j].second==i)
                    result.push_back(j);
            }
        }
        return result;
    }
    void dfs(vector<set<int>>& graph,vector<pair<int,int>>& point,int node){
        if(point[node].first==0){
            point[node].first=++count;
            for(auto neigh:graph[node])
                dfs(graph,point,neigh);
            point[node].second=++count;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值