搜索
您的当前位置:首页正文

[LeetCode] 207. Course Schedule

来源:独旅网

Description

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:

解题思路

题意为给定课程数 n 和先导课程数组,数组里每一个元素为 [课程号, 先导课程号],要学习某门课程,需要先学习先导课程,问是否可以完成所有课程。

题目可以转化为有向图,每一个课程为一个顶点,有向边由 先导课程 指向 目标课程,判断该有向图是否有环,无环则可以完成所有课程,否则不能完成。

判断一个有向图是否有环有很多方法,如 DFS、BFS、拓扑排序。这里使用的是拓扑排序的方法,为方便找每个顶点可以到达的顶点,用了一个 unordered_map 将先导课程数组转化为邻接链表形式,也可以用 vector 替代。记录每一个顶点的入度,然后就跟拓扑排序一样了。最后再判断一下入度数组是否有元素不为 0,若有则有环,返回 fasle,否则返回 true

Code

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>> &prerequisites) {
        vector<int> indegree(numCourses, 0);
        unordered_map<int, list<int>> umap;
        queue<int> mq;

        for (int i = 0; i < prerequisites.size(); ++i) {
            if (umap.count(prerequisites[i].second) == 0)
                umap[prerequisites[i].second] = list<int>(1, prerequisites[i].first);
            else
                umap[prerequisites[i].second].push_back(prerequisites[i].first);
            indegree[prerequisites[i].first]++;
        }

        for (int i = 0; i < numCourses; ++i) {
            if (indegree[i] == 0) mq.push(i);
        }

        while (!mq.empty()) {
            int start = mq.front();
            mq.pop();

            for (auto it = umap[start].begin(); it != umap[start].end(); ++it) {
                indegree[*it]--;
                if (indegree[*it] == 0) mq.push(*it);
            }
        }

        for (auto x: indegree) if (x != 0) return false;
        return true;
    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容

Top