Created
June 4, 2020 10:32
Graph algorithms
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
/** | |
* Author : T Karthikeyan | |
**/ | |
#include<iostream> | |
#include<bits/stdc++.h> | |
using namespace std; | |
void DFS(vector<int>adj[], int v); // finishing time | |
void DFSCC(vector<int>adjt[], int u); // printing SCC | |
vector<int>order; | |
int globalcounter = 0; | |
bool visited[100001] = {0}; // keep track of visited nodes | |
int main() | |
{ | |
//input graph | |
int n, m; | |
int u, v; | |
cin >> n >> m; | |
vector<int>adj[n+1]; // graph | |
vector<int>adjt[n+1]; // transpose graph | |
for(int i = 1; i <= m; i++) | |
{ | |
cin >> u >> v; | |
adj[u].push_back(v); | |
adjt[v].push_back(u); | |
} | |
// finish time | |
for(int i = 1; i <= n; i++) | |
{ | |
if(visited[i] == false) | |
DFS(adj, i); | |
} | |
// re initialising visited array for further use | |
for(int i = 1; i <= n; i++) | |
visited[i] = false; | |
// finding scc | |
cout << endl; | |
reverse(order.begin(), order.end()); | |
int K = 1; | |
for(auto k = order.begin(); k!=order.end(); k++) | |
{ | |
if(visited[*k] == false) | |
{ | |
cout << "SCC "<< (K++)<< " : "; | |
DFSCC(adjt, *k); | |
cout << endl; | |
} | |
} | |
return 0; | |
} | |
void DFS(vector<int>adj[], int v) | |
{ | |
visited[v] = true; | |
for(int i = 0; i < adj[v].size(); i++) | |
{ | |
int u = adj[v][i]; | |
if(visited[u]) | |
continue; | |
visited[u] = true; | |
DFS(adj, u); | |
} | |
order.push_back(v); | |
} | |
void DFSCC(vector<int>adjt[], int u) | |
{ | |
visited[u] = true; | |
cout << u << " "; | |
for(int i = 0; i < adjt[u].size(); i++) | |
{ | |
int w = adjt[u][i]; | |
if(visited[w] == false) | |
DFSCC(adjt, w); | |
} | |
} |
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
8 10 | |
1 3 | |
3 2 | |
2 4 | |
4 3 | |
1 7 | |
6 7 | |
7 5 | |
6 5 | |
5 8 | |
8 7 |
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
SCC 1 : 6 | |
SCC 2 : 1 | |
SCC 3 : 7 8 5 | |
SCC 4 : 3 4 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment