|
| 1 | +package graph_bridges; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | + |
| 6 | +public class FindCutPoints { |
| 7 | + |
| 8 | + private Graph G; |
| 9 | + private boolean[] visited; |
| 10 | + |
| 11 | + private int ord[]; |
| 12 | + private int low[]; |
| 13 | + private int cnt; |
| 14 | + |
| 15 | + private HashSet<Integer> res; |
| 16 | + |
| 17 | + public FindCutPoints(Graph G) { |
| 18 | + |
| 19 | + this.G = G; |
| 20 | + visited = new boolean[G.V()]; |
| 21 | + ord = new int[G.V()]; |
| 22 | + low = new int[G.V()]; |
| 23 | + cnt = 0; |
| 24 | + res = new HashSet<>(); |
| 25 | + |
| 26 | + for (int v = 0; v < G.V(); v++) |
| 27 | + if (!visited[v]) |
| 28 | + dfs(v, v); |
| 29 | + } |
| 30 | + |
| 31 | + private void dfs(int v, int parent) { |
| 32 | + visited[v] = true; |
| 33 | + ord[v] = cnt; |
| 34 | + low[v] = ord[v]; |
| 35 | + cnt++; |
| 36 | + |
| 37 | + int child = 0; |
| 38 | + for (int w : G.adj(v)) { |
| 39 | + if (!visited[w]) { |
| 40 | + dfs(w, v); |
| 41 | + low[v] = Math.min(low[v], low[w]); |
| 42 | + if (v != parent && low[w] >= ord[v]) { |
| 43 | + res.add(v); |
| 44 | + } |
| 45 | + child++; |
| 46 | + if (v == parent && child > 1) |
| 47 | + res.add(v); |
| 48 | + } else if (w != parent) { |
| 49 | + low[v] = Math.min(low[v], low[w]); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public HashSet<Integer> result() { |
| 55 | + return res; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] args) { |
| 59 | + |
| 60 | + Graph g = new Graph("./GraphTheory/src/graph_bridges/g.txt"); |
| 61 | + FindCutPoints fb = new FindCutPoints(g); |
| 62 | + System.out.println(fb.result()); |
| 63 | + |
| 64 | + Graph g2 = new Graph("./GraphTheory/src/graph_bridges/g2.txt"); |
| 65 | + FindCutPoints fb2 = new FindCutPoints(g2); |
| 66 | + System.out.println(fb2.result()); |
| 67 | + |
| 68 | + Graph tree = new Graph("./GraphTheory/src/graph_bridges/tree.txt"); |
| 69 | + FindCutPoints fb3 = new FindCutPoints(tree); |
| 70 | + System.out.println(fb3.result()); |
| 71 | + } |
| 72 | +} |
0 commit comments