題目鏈接: https://leetcode.com/problems/course-schedule/description/
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:
- The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
- You may assume that there are no duplicate edges in the input prerequisites.
解題思路
題意爲給定課程數 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;
}
};