-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBridge.java
126 lines (84 loc) · 2.62 KB
/
Bridge.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.graphs;
import java.util.*;
public class Bridge {
int v;
HashMap<Integer, List<Integer>> adjMap;
int time=0;
static final int NIL =-1;
public Bridge(int v) {
this.v=v;
adjMap = new HashMap<>();
for(int i=0; i<v; i++) {
adjMap.put(i, new LinkedList<>());
}
}
void addEdge(int v, int w) {
adjMap.get(v).add(w);
adjMap.get(w).add(v);
}
void bridge() {
int[] disc = new int[v];
boolean[] visited = new boolean[v];
int[] low = new int[v];
int[] parent = new int[v];
for(int i=0; i<v; i++) {
parent[i]=NIL;
visited[i]=false;
if(!visited[i])
dsfBdrigeUtil(i, low, disc, parent, visited);
}
}
private void dsfBdrigeUtil(int u, int[] low, int[] disc, int[] parent, boolean[] visited) {
visited[u]=true;
disc[u]=low[u]=++time;
List<Integer> list = adjMap.get(u);
Iterator<Integer> itr = list.listIterator();
while(itr.hasNext()) {
int v = itr.next();
if(!visited[v]) {
parent[v]=u;
//dfs
dsfBdrigeUtil(v, low, disc, parent, visited);
// Check if the subtree rooted with v has a
// connection to one of the ancestors of u
low[u] = Math.min(low[u], low[v]);
// If the lowest vertex reachable from subtree
// under v is below u in DFS tree, then u-v is
// a bridge
if (low[v] > disc[u])
System.out.println(u+" "+v);
} else if (v != parent[u]) {
low[u]=Math.min(low[v], disc[u]);
}
}
}
public static void main(String[] args) {
System.out.println("Bridges in first graph ");
Bridge g1 = new Bridge(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(2, 1);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
g1.bridge();
System.out.println();
System.out.println("Bridges in Second graph");
Bridge g2 = new Bridge(4);
g2.addEdge(0, 1);
g2.addEdge(1, 2);
g2.addEdge(2, 3);
g2.bridge();
System.out.println();
System.out.println("Bridges in Third graph ");
Bridge g3 = new Bridge(7);
g3.addEdge(0, 1);
g3.addEdge(1, 2);
g3.addEdge(2, 0);
g3.addEdge(1, 3);
g3.addEdge(1, 4);
g3.addEdge(1, 6);
g3.addEdge(3, 5);
g3.addEdge(4, 5);
g3.bridge();
}
}