Created
September 13, 2019 11:27
-
-
Save sazid/fd74b314a4b0ccb818d5e5a44fd03a56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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