Skip to content

Instantly share code, notes, and snippets.

@sazid
Created September 13, 2019 11:27
Show Gist options
  • Save sazid/fd74b314a4b0ccb818d5e5a44fd03a56 to your computer and use it in GitHub Desktop.
Save sazid/fd74b314a4b0ccb818d5e5a44fd03a56 to your computer and use it in GitHub Desktop.
// Holds the graph
map<char, vector<char>> graph;
// Status of each node - UNVISITED, VISITING, VISITED
map<char, int> status;
// This will denote whether the graph has cycles
bool hasCycles = false;
// Status codes
const int UNVISITED = 0;
const int VISITING = 1;
const int VISITED = 2;
void dfs(char node) {
status[node] = VISITING;
for (char child : graph[node]) {
if (status[child] == UNVISITED)
dfs(child);
else if (status[child] == VISITING) {
hasCycles = true;
return;
}
}
status[node] = VISITED;
}
int main() {
// Input graph here
for (char c : {'A', 'B', 'C'})
if (status[c] == UNVISITED)
dfs(c);
if (hasCycles) {
// Do something
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment