Course Schedule(leetcode)

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

猜你喜欢

转载自blog.csdn.net/joker_yy/article/details/78844018
今日推荐