Skip to content

Commit 56b7cef

Browse files
Implemented Graph Articulation point checking Algorithm in graph folder
1 parent cebd90e commit 56b7cef

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.thealgorithms.graph;
2+
import java.util.Arrays;
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class ArticulationPoint {
7+
// Inner class to represent an edge
8+
class Edge {
9+
int src;
10+
int dest;
11+
12+
public Edge(int s, int d) {
13+
this.src = s;
14+
this.dest = d;
15+
}
16+
}
17+
18+
public static void dfs(ArrayList<Edge>[] graph, int curr, int par, int[] dt, int[] low, boolean[] vis, int time,
19+
List<List<Integer>> res) {
20+
vis[curr] = true;
21+
dt[curr] = low[curr] = ++time;
22+
for (int i = 0; i < graph[curr].size(); i++) {
23+
Edge e = graph[curr].get(i);
24+
int neigh = e.dest;
25+
if (neigh == par) {
26+
continue;
27+
} else if (!vis[neigh]) {
28+
dfs(graph, neigh, curr, dt, low, vis, time, res);
29+
low[curr] = Math.min(low[neigh], low[curr]);
30+
if (dt[curr] < low[neigh]) {
31+
ArrayList<Integer> pair = new ArrayList<>();
32+
pair.add(curr);
33+
pair.add(neigh);
34+
res.add(pair);
35+
}
36+
} else {
37+
low[curr] = Math.min(low[curr], dt[neigh]);
38+
}
39+
}
40+
}
41+
42+
public static List<List<Integer>> tarjans(ArrayList<Edge>[] graph, int V) {
43+
List<List<Integer>> res = new ArrayList<>();
44+
int dt[] = new int[V];
45+
int low[] = new int[V];
46+
int time = 0;
47+
boolean vis[] = new boolean[V];
48+
for (int i = 0; i < V; i++) {
49+
if (!vis[i]) {
50+
dfs(graph, i, -1, dt, low, vis, time, res);
51+
}
52+
}
53+
return res;
54+
}
55+
56+
public List<List<Integer>> criticalConnections(int n, List<List<Integer>> connections) {
57+
ArrayList<Edge>[] graph = new ArrayList[n];
58+
for (int i = 0; i < graph.length; i++) {
59+
graph[i] = new ArrayList<>();
60+
}
61+
for (List<Integer> list : connections) {
62+
int u = list.get(0);
63+
int v = list.get(1);
64+
graph[u].add(new Edge(u, v));
65+
graph[v].add(new Edge(v, u));
66+
}
67+
return tarjans(graph, n);
68+
}
69+
70+
}

0 commit comments

Comments
 (0)