From 354fd0c745c6719744c0ea388c62739b10af40d4 Mon Sep 17 00:00:00 2001 From: puneet1747 Date: Fri, 8 Oct 2021 11:17:49 +0530 Subject: [PATCH] Added bridges code --- Graphs Algos/Bridges.cpp | 59 ++++++++++++++++++++++++++++++++++++++++ Graphs Algos/README.md | 2 +- README.md | 1 + 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 Graphs Algos/Bridges.cpp diff --git a/Graphs Algos/Bridges.cpp b/Graphs Algos/Bridges.cpp new file mode 100644 index 0000000..8befbbb --- /dev/null +++ b/Graphs Algos/Bridges.cpp @@ -0,0 +1,59 @@ +// Find bridges in an undirected graph +vector> bridge; +vector low(n, 0), disc(n, 0); +int timer = 1; + +void dfs_bridge(int cur, int prev) // Run this for each connected component +{ + disc[cur] = low[cur] = timer++; + for (int next : adj[cur]) + { + if (disc[next] == 0) + { + dfs_bridge(next, cur); + low[curr] = min(low[curr], low[next]); + } + else if (next != prev) // Back edges can never be bridges, so we have to check only tree edges + { + low[curr] = min(low[curr], disc[next]); //checking backedge with its ancestor node, and not parent node bcz we are considering parent child as current edge + } + + if (low[next] > disc[cur]) + bridge.push_back({cur, next}); + } +} +/* +Example : +Problem - https://leetcode.com/problems/critical-connections-in-a-network/ +Solution : +class Solution { +public: + vector> criticalConnections(int n, vector>& connections) { + disc = vector(n); + low = vector(n); + for (auto conn : connections) { + edgeMap[conn[0]].push_back(conn[1]); + edgeMap[conn[1]].push_back(conn[0]); + } + dfs(0, -1); + return ans; + } + void dfs(int curr, int prev) { + disc[curr] = low[curr] = time++; + for (int next : edgeMap[curr]) { + if (disc[next] == 0) { + dfs(next, curr); + low[curr] = min(low[curr], low[next]); + } else if (next != prev) //if visited, but not parent, can be ancestor (back edge) + low[curr] = min(low[curr], disc[next]); //min of ancestoe in time(or discovery) + if (low[next] > disc[curr]) //if child ka low time should be greater than in time of parent , tabhi cycle mai nahe rahenga + ans.push_back({curr, next}); + } + } +private: + vector disc{0}, low{0}; + int time = 1; + vector> ans; + unordered_map> edgeMap; +}; +*/ \ No newline at end of file diff --git a/Graphs Algos/README.md b/Graphs Algos/README.md index a91981f..ea7d733 100644 --- a/Graphs Algos/README.md +++ b/Graphs Algos/README.md @@ -28,7 +28,7 @@ - Branch and bound - and many approxiation algorithms -### 6) Bridges +### 6) Bridges ✔️ - DFS No of Components ✔️ ### 7) Articulation points diff --git a/README.md b/README.md index 3fbf12c..dc1f17c 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ This Repo is For those who want to contribute in an open Source Repo for Hacktob ├── bfs-shorteat-path-grid.cpp ├── bfs-shortest-path-list.cpp ├── bipartite-graph-dfs.cpp + ├── bridges.cpp ├── cycles-one-dfs.cpp ├── dfs-recursion-list.cpp ├── dijkstra-shortest-path-dfs.cpp