No210. Course Schedule II

来源:互联网 发布:潍坊行知中学新校区 编辑:程序博客网 时间:2024/05/16 10:50

一、题目描述

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;        }    }};


原创粉丝点击