diff --git a/C-Plus-Plus/StronglyConnectedComponents.cpp b/C-Plus-Plus/StronglyConnectedComponents.cpp new file mode 100644 index 00000000..74fb47e4 --- /dev/null +++ b/C-Plus-Plus/StronglyConnectedComponents.cpp @@ -0,0 +1,65 @@ +/* + Strongly Connected Components + Author: Johnny Villegas + Github: Jvillegasd +*/ + +#include + +using namespace std; + +int NUM_NODES = 100 +vector g[NUM_NODES], rg[NUM_NODES]; +bool visited[NUM_NODES]; +stack s; + +void DFS(int u) { + visited[u] = true; + for(auto v : g[u]) { + if (!visited[v]) { + DFS(v); + } + } + s.push(u); +} + +void DFS_inv(int u) { + visited[u] = true; + print("Node: %d\n", u); + for(auto v : rg[u]) { + if (!visited[v]) { + DFS_inv(v); + } + } +} + +void SCC() { + int comp = 1; + for (int u = 1; u <= NUM_NODES; u++) { + if (!visited[u]) { + DFS(u); + } + } + memset(visited, 0, sizeof(visited)); + while(!s.empty()) { + int u = s.top(); + s.pop(); + if (visited[u]) { + continue; + } + printf("Component #%d:\n", comp++); + DFS_inv(u); + printf("\n"); + } +} + +int main() { + /* + This is the SCC Kosajaru algorithm. Before to run it, you have to + fill DAG "g" and its reverse "rg". Reverse DAG is the same DAG "g" but + edges are pointing to oppposite direction. + */ + + SCC(); + return 0; +}