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.
click to show more hints.
Hints:
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.
問題描述及算法分析
課程清單這題是典型的拓撲排序,本題Note中也提到其實質就是判斷在一個有向圖中是否有環。拓撲排序有兩個基本操作:決定一個頂點是否入度爲0和刪除一個頂點的所有出邊。即在有向圖中每次找到一個入度爲0的節點,然後把它指向其他節點的邊都去掉,重複這個過程,直到所有節點已被找到,或者沒有符合條件的節點(有環存在)。
算法採用隊列存儲節點可降低複雜度,二維數組vector<vector<int>>
表示一個圖,用一維數組vector<int>
記錄入度的個數,定義一個queue變量,將所有入度爲0的點放入隊列中,然後開始遍歷隊列,從graph裏遍歷其連接的點,每到達一個新節點,將其入度減一,如果此時該點入度爲0,則放入隊列末尾。直到遍歷完隊列中所有的值,若此時還有節點的入度不爲0,則說明環存在,返回false,反之則返回true。
代碼
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses,0);
for(auto i : prerequisites) {
graph[i.first].push_back(i.second);
indegree[i.second]++;
}
queue<int> q;
for (auto a = 0; a < numCourses;a++) {
if (indegree[a] == 0) {
q.push(a);
}
}
int count = 0;
while (!q.empty()) {
int temp = q.front();
q.pop();
count++;
for(auto v : graph[temp]) {
indegree[v]--;
if (indegree[v] == 0) {
q.push(v);
}
}
}
return count == numCourses;
}
};
【易錯點】vector容器的賦值及遍歷操作;隊列的聲明、入隊及出隊操作
其他算法分析
可採用DFS算法實現
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> graph(numCourses);
vector<int> visited(numCourses, 0);
for (auto a : prerequisites) {
graph[a.second].push_back(a.first);
}
bool cycle = false;
for (auto b = 0; b < numCourses; b++) {
if (cycle) return false;
if (visited[b] == 0) {
DFS(b,graph,cycle,visited);
}
}
return !cycle;
}
void DFS(int node, vector<vector<int>>& graph, bool & cycle, vector<int> & visited) {
if(visited[node] == 1) {
cycle = true;
return;
}
visited[node] = 1;
for (auto i : graph[node]) {
DFS(i,graph,cycle,visited);
if(cycle) return;
}
visited[node] = 2;
}
};