forked from sukritishah15/DS-Algo-Point
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create StronglyConnectedComponents.cpp
- Loading branch information
1 parent
31648a5
commit c38c1da
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} |