-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCutEdge.java
More file actions
108 lines (90 loc) · 2.48 KB
/
Copy pathCutEdge.java
File metadata and controls
108 lines (90 loc) · 2.48 KB
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
import java.util.ArrayList;
public class CutEdge {
private int ids[];
private int lows[];
private int id;
private boolean visited[];
private ArrayList<Edge> cutEdgeList;
public int min (int a, int b) {
return a < b ? a : b;
}
static class Edge {
private int from;
private int to;
public Edge(int from, int to) {
this.from = from;
this.to = to;
}
}
public void dfs (Graph graph, int cur, int parent) {
visited[cur] = true;
ids[cur] = id;
lows[cur] = id;
id++;
for (int to : graph.graph[cur]) {
if (parent == to)
continue;
if (!visited[to]) {
dfs(graph, to, cur);
lows[cur] = min(lows[cur], lows[to]);
if (ids[cur] < lows[to])
cutEdgeList.add(new Edge(cur, to));
}else {
lows[cur] = min(ids[to], lows[cur]);
}
}
}
public void doCutEdgeAlgorithm(Graph graph, int n) {
ids = new int[n];
lows = new int[n];
visited = new boolean[n];
cutEdgeList = new ArrayList<>();
// Seek Cut Edge
dfs(graph, 0, -1);
// Print Cut Edge
// Output will be : 3-4 2-3 2-5
for (Edge cutEdge : cutEdgeList) {
System.out.print(cutEdge.from + "-" + cutEdge.to + " ");
}
}
// For construct graph
static class Graph {
private ArrayList<Integer> graph[];
public Graph(int n) {
graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
}
public void addEdge(int a, int b) {
graph[a].add(b);
graph[b].add(a);
}
}
/*
Sample Graph
0 6
/ \ / \
1 - 2 - 5 7 ==> Cut Edge will be 3-4, 2-3, 2-5
| \ /
3 8
\
4
*/
public static void main(String[] args) {
int n = 9;
Graph graph = new Graph(n);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(2, 5);
graph.addEdge(3, 4);
graph.addEdge(5, 6);
graph.addEdge(5, 8);
graph.addEdge(6, 7);
graph.addEdge(7, 8);
CutEdge cutEdge = new CutEdge();
cutEdge.doCutEdgeAlgorithm(graph, n);
}
}