Course Schedule(leetcode)

来源:互联网 发布:苹果自动拨号软件 编辑:程序博客网 时间:2024/05/22 13:52

Course Schedule

  • Course Schedule
    • 题目
    • 解决


题目

leetcode题目

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.

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

解决

求图的拓扑排序。

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<unordered_set<int>> graph = makeGraph(numCourses, prerequisites);        vector<int> degrees = computeIndegree(graph);        for (int i = 0; i < numCourses; i++) {            int temp = 0;            for (; temp < numCourses; temp++) {                if (degrees[temp] == 0) break;            }            if (temp == numCourses) {                return false;            }            degrees[temp]= -1;            for (unordered_set<int>::iterator it = graph[temp].begin(); it != graph[temp].end(); it++) {                degrees[*it]--;            }        }        return true;    }    vector<unordered_set<int>> makeGraph(int n, vector<pair<int, int>>& edges) {        vector<unordered_set<int>> result(n);        int num = edges.size();        for (int i = 0; i < num; i++) {            result[edges[i].second].insert(edges[i].first);        }        return result;    }    vector<int> computeIndegree(vector<unordered_set<int>> graph) {        int num = graph.size();        vector<int> result(num, 0);        for (int i = 0; i < num; i++) {            for (unordered_set<int>::iterator it = graph[i].begin(); it != graph[i].end(); it++) {                result[*it]++;            }        }        return result;    }};