1. All-Pairs Reachability Intersection
Intuition
For every pair of vertices (u, v), run BFS to check if u can reach v and v can reach u. Group mutually reachable nodes into SCCs.
Algorithm
- Compute boolean reachability matrix reachable[u][v] by running BFS from each vertex u.
- Maintain a visited set of grouped vertices.
- For each unvisited vertex u:
- Collect all unvisited vertices v where reachable[u][v] && reachable[v][u].
- Mark all collected vertices as visited and increment SCC count.
- Return SCC count.
#include <iostream>#include <vector>#include <queue> using namespace std; void bfs(int src, const vector<vector<int>>& adj, vector<bool>& reachable) { queue<int> q; q.push(src); reachable[src] = true; while (!q.empty()) { int u = q.front(); q.pop(); for (int v : adj[u]) { if (!reachable[v]) { reachable[v] = true; q.push(v); } } }} int countSCCsBruteForce(int V, const vector<vector<int>>& adj) { vector<vector<bool>> reachable(V, vector<bool>(V, false)); for (int i = 0; i < V; ++i) { bfs(i, adj, reachable[i]); } vector<bool> visited(V, false); int sccCount = 0; for (int i = 0; i < V; ++i) { if (!visited[i]) { sccCount++; for (int j = 0; j < V; ++j) { if (reachable[i][j] && reachable[j][i]) { visited[j] = true; } } } } return sccCount;} int main() { int V = 5; vector<vector<int>> adj = {{2, 3}, {0}, {1}, {4}, {}}; cout << "SCC Count (Brute Force): " << countSCCsBruteForce(V, adj) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(V * (V + E)) - Space complexity:
O(V^2)