-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
85 lines (66 loc) · 2.17 KB
/
Copy pathsolution.java
File metadata and controls
85 lines (66 loc) · 2.17 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
class Solution {
static int timer;
static void dfs(int node, int parent, ArrayList<Integer>[] adj,
boolean[] vis, int[] tin, int[] low, boolean[] mark) {
vis[node] = true;
tin[node] = low[node] = timer++;
int childCount = 0;
for (int neighbor : adj[node]) {
// Ignore parent edge
if (neighbor == parent)
continue;
// Already visited node
if (vis[neighbor]) {
low[node] = Math.min(low[node], tin[neighbor]);
}
else {
dfs(neighbor, node, adj, vis, tin, low, mark);
// Update low value
low[node] = Math.min(low[node], low[neighbor]);
// Articulation point condition for non-root
if (low[neighbor] >= tin[node] && parent != -1) {
mark[node] = true;
}
childCount++;
}
}
// Root node condition
if (parent == -1 && childCount > 1) {
mark[node] = true;
}
}
static ArrayList<Integer> articulationPoints(int V, int[][] edges) {
timer = 0;
ArrayList<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
// Build adjacency list
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
adj[u].add(v);
adj[v].add(u);
}
boolean[] vis = new boolean[V];
int[] tin = new int[V];
int[] low = new int[V];
boolean[] mark = new boolean[V];
// DFS for disconnected graph
for (int i = 0; i < V; i++) {
if (!vis[i]) {
dfs(i, -1, adj, vis, tin, low, mark);
}
}
ArrayList<Integer> ans = new ArrayList<>();
for (int i = 0; i < V; i++) {
if (mark[i]) {
ans.add(i);
}
}
if (ans.size() == 0) {
ans.add(-1);
}
return ans;
}
}