Skip to content

Commit

Permalink
Create StronglyConnectedComponents.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
jvillegasd committed Oct 3, 2020
1 parent 31648a5 commit c38c1da
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions C-Plus-Plus/StronglyConnectedComponents.cpp
@@ -0,0 +1,65 @@
/*
Strongly Connected Components
Author: Johnny Villegas
Github: Jvillegasd
*/

#include <bits/stdc++.h>

using namespace std;

int NUM_NODES = 100
vector<int> g[NUM_NODES], rg[NUM_NODES];
bool visited[NUM_NODES];
stack<int> 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;
}

0 comments on commit c38c1da

Please sign in to comment.