landscapemi的博客

###### leetcode_c++:图：Course Schedule(207)

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.

//学习课程A要先学课程B，给出一个课程学习顺序，问这些课程能不能学完

### 算法

DFS的算法

class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
if (numCourses == 0 || prerequisites.empty())
return true;
graph = vector<vector<int> >(numCourses);
vis = vector<int>(numCourses, 0); // not visit
for (auto i : prerequisites) {
graph[i.second].push_back(i.first);
}
for (int u = 0; u < numCourses; ++u) {
if (0 == vis[u] && !dfs(u))
return false;
}
return true;
}
private:
vector<vector<int> > graph;
vector<int> vis;
bool dfs(int u) {
vis[u] = 1; // visiting
for (auto v : graph[u]) {
if (vis[v] == 1)
return false;
if (dfs(v) == false)
return false;
}
vis[u] = 2; // visited
return true;
};
};

#### 【LeetCode】207. Course Schedule

2016-05-30 23:40:09

#### leetcode 207: Course Schedule

2015-05-20 05:07:51

#### leetcode_c++:图：Course Schedule II (207)

2016-08-28 15:11:38

#### Leetcode解题报告：207. Course Schedule

2016-11-26 23:47:38

#### [LeetCode]207. Course Schedule 课程表

2018-03-03 21:52:47

#### [leetcode] 207. Course Schedule 解题报告

2016-02-26 14:10:16

#### LeetCode 207、Course Schedule 题解

2017-03-12 12:29:16

#### LeetCode 207 - Course Schedule

2015-05-07 02:24:40

#### leetcode的C++答案

2016年09月06日 866KB 下载

#### LeetCode 207 Course Schedule

2017-03-18 17:40:19

## 不良信息举报

leetcode_c++:图：Course Schedule(207)