-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
97 lines (80 loc) · 3.07 KB
/
Graph.java
File metadata and controls
97 lines (80 loc) · 3.07 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
// A Java program to find articulation
// points in an undirected graph
import java.util.*;
import java.io.*;
class Graph {
static int time;
static void addEdge(ArrayList<ArrayList<Integer> > adj, int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void APUtil(ArrayList<ArrayList<Integer> > adj, int u,
boolean visited[], int disc[], int low[],
int parent, boolean isAP[])
{
// Count of children in DFS Tree
int children = 0;
// Mark the current node as visited
visited[u] = true;
// Initialize discovery time and low value
disc[u] = low[u] = ++time;
// Go through all vertices aadjacent to this
for (Integer v : adj.get(u)) {
// If v is not visited yet, then make it a child of u
// in DFS tree and recur for it
if (!visited[v]) {
children++;
APUtil(adj, v, visited, disc, low, u, isAP);
// 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 u is not root and low value of one of
// its child is more than discovery value of u.
if (parent != -1 && low[v] >= disc[u])
isAP[u] = true;
}
// Update low value of u for parent function calls.
else if (v != parent)
low[u] = Math.min(low[u], disc[v]);
}
// If u is root of DFS tree and has two or more children.
if (parent == -1 && children > 1)
isAP[u] = true;
}
static void AP(ArrayList<ArrayList<Integer> > adj, int V)
{
boolean[] visited = new boolean[V];
int[] disc = new int[V];
int[] low = new int[V];
boolean[] isAP = new boolean[V];
int time = 0, par = -1;
// Adding this loop so that the
// code works even if we are given
// disconnected graph
for (int u = 0; u < V; u++)
if (visited[u] == false)
APUtil(adj, u, visited, disc, low, par, isAP);
for (int u = 0; u < V; u++)
if (isAP[u] == true)
System.out.print(u + " ");
System.out.println();
}
public static void main(String[] args)
throws FileNotFoundException{
// Creating first example graph
Scanner sc = new Scanner(new File(args[0]));
int V = 5;
ArrayList<ArrayList<Integer> > adj1 =
new ArrayList<ArrayList<Integer> >(V);
for (int i = 0; i < V; i++)
adj1.add(new ArrayList<Integer>());
addEdge(adj1, 1, 0);
addEdge(adj1, 0, 2);
addEdge(adj1, 2, 1);
addEdge(adj1, 0, 3);
addEdge(adj1, 3, 4);
System.out.println("Articulation points in first graph");
AP(adj1, V);
}
}