|
| 1 | +class Solution { |
| 2 | + public: |
| 3 | + // Depth First Search to find articulation points |
| 4 | + void DSF(int node, int parent, int& timer, vector<int>& disc, vector<int>& low, vector<int>& visited, vector<int>& AP, vector<vector<int>>& adjacencyList) { |
| 5 | + visited[node] = true; // Mark the node as visited |
| 6 | + disc[node] = low[node] = timer++; // Assign discovery time and initialize low |
| 7 | + int child = 0; // Count of children in DFS tree |
| 8 | + |
| 9 | + // Traverse all neighbors of the current node |
| 10 | + for (auto neighbour : adjacencyList[node]) { |
| 11 | + if (neighbour == parent) continue; // Skip the parent node |
| 12 | + |
| 13 | + if (!visited[neighbour]) { // If the neighbor is not visited |
| 14 | + DSF(neighbour, node, timer, disc, low, visited, AP, adjacencyList); // Recursively visit |
| 15 | + low[node] = min(low[node], low[neighbour]); // Update low value for the current node |
| 16 | + |
| 17 | + // Check articulation point condition |
| 18 | + if (low[neighbour] >= disc[node] && parent != -1) { |
| 19 | + if (find(AP.begin(), AP.end(), node) == AP.end()) AP.push_back(node); |
| 20 | + } |
| 21 | + child++; |
| 22 | + } else { |
| 23 | + low[node] = min(low[node], disc[neighbour]); // Update low value if back edge exists |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + // Check root node condition |
| 28 | + if (parent == -1 && child > 1) { |
| 29 | + if (find(AP.begin(), AP.end(), node) == AP.end()) AP.push_back(node); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Main function to find articulation points |
| 34 | + vector<int> articulationPoints(int V, vector<int> adj[]) { |
| 35 | + vector<int> disc(V, -1); // Discovery times |
| 36 | + vector<int> low(V, -1); // Lowest discovery times |
| 37 | + vector<int> visited(V, false); // Visited nodes |
| 38 | + vector<int> AP; // Articulation points |
| 39 | + int timer = 0; // Timer to assign discovery times |
| 40 | + vector<vector<int>> adjacencyList(V); |
| 41 | + |
| 42 | + // Convert adjacency list |
| 43 | + for (int i = 0; i < V; i++) { |
| 44 | + for (auto neighbour : adj[i]) adjacencyList[i].push_back(neighbour); |
| 45 | + } |
| 46 | + |
| 47 | + // Perform DFS for all connected components |
| 48 | + for (int i = 0; i < V; i++) { |
| 49 | + if (!visited[i]) { |
| 50 | + DSF(i, -1, timer, disc, low, visited, AP, adjacencyList); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // If no articulation points found, return {-1} |
| 55 | + if (AP.empty()) AP.push_back(-1); |
| 56 | + else sort(AP.begin(), AP.end()); // Sort the articulation points |
| 57 | + |
| 58 | + return AP; |
| 59 | + } |
| 60 | +}; |
0 commit comments