|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Depth-First Search (DFS) function to explore the graph |
| 4 | + void dfs(int node, int parent, int timer, int& result, vector<int>& visited, vector<int>& disc, vector<int>& low, vector<vector<int>>& adjacencyList, int c, int d){ |
| 5 | + visited[node] = true; // Mark the current node as visited |
| 6 | + disc[node] = low[node] = timer++; // Set discovery time and low time of the node |
| 7 | + |
| 8 | + // Traverse all adjacent vertices (neighbors) of the current node |
| 9 | + for(int vertex : adjacencyList[node]){ |
| 10 | + if(vertex == parent) continue; // Skip the parent node to avoid going backward in the DFS |
| 11 | + |
| 12 | + if(!visited[vertex]){ // If the neighbor is unvisited, perform DFS on it |
| 13 | + dfs(vertex, node, timer, result, visited, disc, low, adjacencyList, c, d); |
| 14 | + low[node] = min(low[node], low[vertex]); // Update the low time of the current node |
| 15 | + |
| 16 | + // If low value of the neighbor is greater than the discovery time of the current node |
| 17 | + // and the edge (node, vertex) is the target edge (c, d), set result to 1 (indicating it's a bridge) |
| 18 | + if(low[vertex] > disc[node] && ((node == c && vertex == d) || (node == d && vertex == c))) |
| 19 | + result = 1; |
| 20 | + } else { |
| 21 | + low[node] = min(low[node], disc[vertex]); // Update the low time if the neighbor is already visited |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // Function to check if the edge (c, d) is a bridge |
| 27 | + int isBridge(int V, vector<int> adj[], int c, int d) { |
| 28 | + vector<int> disc(V, -1); // Discovery time for each vertex (initially -1, indicating unvisited) |
| 29 | + vector<int> low(V, -1); // Lowest discovery time reachable from the vertex (initially -1) |
| 30 | + vector<int> visited(V, false); // To keep track of visited nodes |
| 31 | + int result = 0; // Variable to store the result (0 means no bridge, 1 means it's a bridge) |
| 32 | + |
| 33 | + vector<vector<int>> adjacencyList(V); // Adjacency list to represent the graph |
| 34 | + |
| 35 | + // Build the adjacency list from the given edge list |
| 36 | + for(int i = 0; i < V; i++){ |
| 37 | + for(auto& vertex : adj[i]){ |
| 38 | + adjacencyList[i].push_back(vertex); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Perform DFS from every unvisited node |
| 43 | + for(int i = 0; i < V; i++) |
| 44 | + if(!visited[i]) |
| 45 | + dfs(i, -1, 0, result, visited, disc, low, adjacencyList, c, d); |
| 46 | + |
| 47 | + return result; // Return 1 if the edge (c, d) is a bridge, else return 0 |
| 48 | + } |
| 49 | +}; |
0 commit comments