1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include <iostream> #include <vector> #include <stack> using namespace std;
class Graph { int V; vector<int> *adj; void SCCUtil(int u, int disc[], int low[], stack<int> *st, bool stackMember[]);
public: Graph(int V); void addEdge(int v, int w); void SCC(); };
Graph::Graph(int V) { this->V = V; adj = new vector<int>[V]; }
void Graph::addEdge(int v, int w) { adj[v].push_back(w); }
void Graph::SCCUtil(int u, int disc[], int low[], stack<int> *st, bool stackMember[]) { static int time = 0; disc[u] = low[u] = ++time; st->push(u); stackMember[u] = true;
for (int i : adj[u]) { if (disc[i] == -1) { SCCUtil(i, disc, low, st, stackMember); low[u] = min(low[u], low[i]); } else if (stackMember[i]) { low[u] = min(low[u], disc[i]); } }
int w = 0; if (low[u] == disc[u]) { while (st->top() != u) { w = st->top(); cout << w << " "; stackMember[w] = false; st->pop(); } w = st->top(); cout << w << "\n"; stackMember[w] = false; st->pop(); } }
void Graph::SCC() { int *disc = new int[V]; int *low = new int[V]; bool *stackMember = new bool[V]; stack<int> *st = new stack<int>();
for (int i = 0; i < V; i++) { disc[i] = -1; low[i] = -1; stackMember[i] = false; }
for (int i = 0; i < V; i++) { if (disc[i] == -1) { SCCUtil(i, disc, low, st, stackMember); } } }
int main() { Graph g(5); g.addEdge(1, 0); g.addEdge(0, 2); g.addEdge(2, 1); g.addEdge(0, 3); g.addEdge(3, 4);
cout << "Strongly Connected Components in the given graph are:\n"; g.SCC();
return 0; }
|