Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active September 3, 2015 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junjiah/a60adbb9ea3d93161d9a to your computer and use it in GitHub Desktop.
Save junjiah/a60adbb9ea3d93161d9a to your computer and use it in GitHub Desktop.
solved 'Course Schedule' on LeetCode https://leetcode.com/problems/course-schedule/
class Solution {
public:
// Use DFS to find cycles.
bool canFinish(int numCourses, vector<pair<int, int>> &prerequisites) {
// Init the graph.
adjacency_list_ = vector<vector<int>>(numCourses);
visited_ = vector<bool>(numCourses);
visited_in_recursion_ = vector<bool>(numCourses);
for (const auto &edge : prerequisites) {
adjacency_list_[edge.second].push_back(edge.first);
}
bool has_back_edge = false;
for (int i = 0; i < numCourses; ++i) {
if (!visited_[i]) {
has_back_edge = hasBackEdge(i);
if (has_back_edge) {
break;
}
}
}
// Having back edges means there are cycles, thus
// impossible to finish the courses.
return !has_back_edge;
}
private:
// Looking for back edges using DFS.
bool hasBackEdge(int v) {
visited_[v] = true;
visited_in_recursion_[v] = true;
for (int neighbor : adjacency_list_[v]) {
if (visited_in_recursion_[neighbor] ||
(!visited_[neighbor] && hasBackEdge(neighbor))) {
// Found a back edge. Note the DFS happens
// in the second condition.
return true;
}
}
// Unmark the recursion records.
visited_in_recursion_[v] = false;
return false;
}
vector<vector<int>> adjacency_list_;
vector<bool> visited_;
vector<bool> visited_in_recursion_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment