TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
bridge_finding_with_tarjan_algorithm.cpp
1/*
2 * Copyright : 2020 , MIT
3 * Author : Amit Kumar (offamitkumar)
4 * Last Modified Date: May 24, 2020
5 *
6 */
7#include <algorithm> // for min & max
8#include <iostream> // for cout
9#include <vector> // for std::vector
10
11class Solution {
12 std::vector<std::vector<int>> graph;
13 std::vector<int> in_time, out_time;
14 int timer = 0;
15 std::vector<std::vector<int>> bridge;
16 std::vector<bool> visited;
17 void dfs(int current_node, int parent) {
18 visited.at(current_node) = true;
19 in_time[current_node] = out_time[current_node] = timer++;
20 for (auto& itr : graph[current_node]) {
21 if (itr == parent) {
22 continue;
23 }
24 if (!visited[itr]) {
25 dfs(itr, current_node);
26 if (out_time[itr] > in_time[current_node]) {
27 bridge.push_back({itr, current_node});
28 }
29 }
30 out_time[current_node] =
31 std::min(out_time[current_node], out_time[itr]);
32 }
33 }
34
35 public:
36 std::vector<std::vector<int>> search_bridges(
37 int n, const std::vector<std::vector<int>>& connections) {
38 timer = 0;
39 graph.resize(n);
40 in_time.assign(n, 0);
41 visited.assign(n, false);
42 out_time.assign(n, 0);
43 for (auto& itr : connections) {
44 graph.at(itr[0]).push_back(itr[1]);
45 graph.at(itr[1]).push_back(itr[0]);
46 }
47 dfs(0, -1);
48 return bridge;
49 }
50};
51
55int main() {
56 Solution s1;
57 int number_of_node = 5;
58 std::vector<std::vector<int>> node;
59 node.push_back({0, 1});
60 node.push_back({1, 3});
61 node.push_back({1, 2});
62 node.push_back({2, 4});
63 /*
64 * 0 <--> 1 <---> 2
65 * ^ ^
66 * | |
67 * | |
68 * \/ \/
69 * 3 4
70 *
71 * In this graph there are 4 bridges [0,2] , [2,4] , [3,5] , [1,2]
72 *
73 * I assumed that the graph is bi-directional and connected.
74 *
75 */
76 std::vector<std::vector<int>> bridges =
77 s1.search_bridges(number_of_node, node);
78 std::cout << bridges.size() << " bridges found!\n";
79 for (auto& itr : bridges) {
80 std::cout << itr[0] << " --> " << itr[1] << '\n';
81 }
82 return 0;
83}
struct node { int data; int height; struct node *left; struct node *right;} node
for std::queue
Definition avltree.cpp:13
int main()
Main function.
Graph Algorithms.