|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to perform DFS |
| 4 | + void dfs(int node, vector<int>& visited, vector<vector<int>>& adjacencyList) { |
| 5 | + visited[node] = true; |
| 6 | + for (auto neighbour : adjacencyList[node]) { |
| 7 | + if (!visited[neighbour]) { |
| 8 | + dfs(neighbour, visited, adjacencyList); |
| 9 | + } |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + // Function to find articulation points using brute force |
| 14 | + vector<int> articulationPoints(int V, vector<int> adj[]) { |
| 15 | + vector<int> AP; // To store articulation points |
| 16 | + vector<vector<int>> adjacencyList(V); |
| 17 | + |
| 18 | + // Convert adj[] to a vector of vectors |
| 19 | + for (int i = 0; i < V; i++) { |
| 20 | + for (auto neighbour : adj[i]) { |
| 21 | + adjacencyList[i].push_back(neighbour); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + // Check each node as a potential articulation point |
| 26 | + for (int i = 0; i < V; i++) { |
| 27 | + vector<int> visited(V, false); // Visited array |
| 28 | + // Temporarily remove node `i` from the graph |
| 29 | + vector<vector<int>> tempAdjList = adjacencyList; |
| 30 | + for (auto& neighbours : tempAdjList) { |
| 31 | + neighbours.erase(remove(neighbours.begin(), neighbours.end(), i), neighbours.end()); |
| 32 | + } |
| 33 | + |
| 34 | + // Perform DFS from a node other than `i` |
| 35 | + int startNode = (i == 0) ? 1 : 0; |
| 36 | + dfs(startNode, visited, tempAdjList); |
| 37 | + |
| 38 | + // Check if any node is not visited |
| 39 | + bool isDisconnected = false; |
| 40 | + for (int j = 0; j < V; j++) { |
| 41 | + if (j != i && !visited[j]) { |
| 42 | + isDisconnected = true; |
| 43 | + break; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // If the graph becomes disconnected, `i` is an articulation point |
| 48 | + if (isDisconnected) { |
| 49 | + AP.push_back(i); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + // If no articulation points found, return {-1} |
| 54 | + if (AP.empty()) { |
| 55 | + AP.push_back(-1); |
| 56 | + } else { |
| 57 | + sort(AP.begin(), AP.end()); |
| 58 | + } |
| 59 | + |
| 60 | + return AP; |
| 61 | + } |
| 62 | +}; |
0 commit comments