第十二周 leetcode 207. Course Schedule(Medium)

来源:互联网 发布:linux 加载u盘 编辑:程序博客网 时间:2024/06/06 06:38

题目描述:

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.

解题思路:
拓扑排序流程:
1.从 DAG 图中选择一个 没有前驱(即入度为0)的顶点并输出。
2.从图中删除该顶点和所有以它为起点的有向边。
3.重复 1 和 2 直到当前的 DAG 图为空或当前图中不存在无前驱的顶点为止。

代码:

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>> E(numCourses);        int num = prerequisites.size();        // record indegree        vector<int> indegree(numCourses, 0);        for (int i = 0; i < num; i++) {            pair<int, int> p = prerequisites[i];            indegree[p.first]++;            E[p.second].push_back(p.first);        }        // find points s.t. indegree=0        queue<int> que;        for (int i = 0; i < numCourses; i++) {            if (indegree[i] == 0) que.push(i);        }        int count = 0;        while (!que.empty()) {            int temp = que.front();            que.pop();            count++;            for (auto st : E[temp]) {                 if (indegree[st] == 1) que.push(st);                indegree[st]--;            }        }        return count == numCourses;    }};

代码运行结果:
这里写图片描述

原创粉丝点击