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
|
import java.util.LinkedList;
class Graph {
private int V; // No. of vertices
private final boolean isDirected;
private LinkedList<Integer> adj[]; //Adjacency List array
//Constructor
Graph(int v) {
this(v, false);
}
Graph(int v, boolean isDirected) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i<v; ++i) {
adj[i] = new LinkedList();
}
isDirected = isDirected;
}
//Function to add an edge into the graph
void addEdge(int src, int dest) {
adj[src].add(dest);
// Since graph is undirected, add an edge from dest
// to src also
if (!isDirected) {
adj[dest].add(src);
}
}
void printGraph() {
for (int v = 0; v<V; v++) {
System.out.println("Adjacency list of vertex " + v);
System.out.print("head");
for (Integer pCrawl: adj[v]) {
System.out.print(" -> " + pCrawl);
}
System.out.println("\n");
}
}
// Driver method
public static void main(String args[]) {
// Create a graph given in the above diagram
Graph g = new Graph(5);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
System.out.println("Following are strongly connected components " +
"in given graph ");
}
}
public class GFG {
// Driver program to test above functions
public static void main(String args[]) {
// create the graph given in above figure
int V = 5;
//undirected graph
Graph graph = new Graph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
// print the adjacency list representation of
// the above graph
printGraph(graph);
}
}
|