Leetcode:207. Course Schedule
2017-06-21 23:29
344 查看
代码:
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
vector<bool> onpath(numCourses, false), visited(numCourses, false);
for (int i = 0; i < numCourses; i++)
if (!visited[i] && dfs_cycle(graph, i, onpath, visited))
return false;
return true;
}
private:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
bool dfs_cycle(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited) {
if (visited[node]) return false;
onpath[node] = visited[node] = true;
for (int neigh : graph[node])
if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited))
return true;
return onpath[node] = false;
}
};
思路:
对图进行一次深度优先搜索,如果存在某个点通过搜素可以搜索到该点本身,则证明图中存在环,否则就是有向无环图
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
vector<bool> onpath(numCourses, false), visited(numCourses, false);
for (int i = 0; i < numCourses; i++)
if (!visited[i] && dfs_cycle(graph, i, onpath, visited))
return false;
return true;
}
private:
vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph(numCourses);
for (auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
bool dfs_cycle(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited) {
if (visited[node]) return false;
onpath[node] = visited[node] = true;
for (int neigh : graph[node])
if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited))
return true;
return onpath[node] = false;
}
};
思路:
对图进行一次深度优先搜索,如果存在某个点通过搜素可以搜索到该点本身,则证明图中存在环,否则就是有向无环图
相关文章推荐
- Leetcode 207. Course Schedule
- LeetCode207. Course Schedule
- Leetcode 207. Course Schedule
- LeetCode 207. Course Schedule(课程安排)
- leetcode 207. Course Schedule
- LeetCode207. Course Schedule
- leetcode 207. Course Schedule
- Leetcode 207. Course Schedule & 210. Course Schedule II
- LeetCode 207. Course Schedule
- LeetCode207. Course Schedule
- leetcode 207. Course Schedule 课程调度 + 拓扑排序
- leetcode 207. Course Schedule
- LeetCode 207. Course Schedule(拓扑排序)
- [leetcode] 207. Course Schedule
- 第十二周 leetcode 207. Course Schedule(Medium)
- Leetcode 207. Course Schedule
- 【LeetCode】207. Course Schedule (2 solutions)
- LeetCode 207. Course Schedule
- leetcode 207. Course Schedule
- [leetcode] 207. Course Schedule 解题报告