210. Course Schedule II 课程安排

来源:互联网 发布:android 线程数据传递 编辑:程序博客网 时间:2024/05/19 18:39

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].



解答:

这里定义两个数据结构,一个是有关顶点出度的邻接链表,另一个是关于记录顶点入度的矩阵。同时访问每个顶点时用队列进行顶点的存储和访问。

编码过程中出过这么些问题:

1.对于节点访问结束后退出循环,没有判断,加入 if(num == 0) break; (判断当全部节点访问过后退出循环)

2.对于走一半就开始有环了的情况,加入 if(stk.empty()) break;   和 if(res.size() < numCourses) res.clear();进行判断

代码如下:


class Solution {public:vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {    //这里定义两个数据结构,一个是有关顶点出度的邻接链表,另一个是关于记录顶点入度的矩阵    vector<int>res;    if(numCourses == 0) return res;    vector<int> ingree(numCourses, 0);    vector<vector<int>> nodelist(numCourses);    for(int i = 0; i < prerequisites.size(); i++){        int a = prerequisites[i].first;        int b = prerequisites[i].second;        ingree[a]++;        nodelist[b].push_back(a);    }    int num = numCourses;    queue<int>stk;    while(num > 0){        for(int i = 0; i < numCourses; i++){            if(ingree[i] == 0){                stk.push(i);                ingree[i] = -1;            }        }        if(stk.empty()) break; //如果队列中是空的(这里包含两种情况:出现环和遍历结束),就退出        while(!stk.empty()){            int temp = stk.front();            stk.pop();            res.push_back(temp);            num--;            if(num == 0) break; //当节点都遍历完了,就退出,此时队列中是空的            for(int i = 0; i < nodelist[temp].size(); i++){                int t = nodelist[temp][i];                if(--ingree[t] == 0){                    stk.push(t);                    ingree[t] = -1;                }            }        }    }    if(res.size() < numCourses) res.clear();//若有环,则清空res中的值    return res;}};




0 0
原创粉丝点击