-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathGraph_Problem_01_i.java
More file actions
50 lines (37 loc) · 1.14 KB
/
Graph_Problem_01_i.java
File metadata and controls
50 lines (37 loc) · 1.14 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
package graphs;
import java.util.*;
// Problem Title :-> Create a Graph, print it
public class Graph_Problem_01_i {
// A utility function to add an edge in an undirected graph
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
adj.get(u).add(v);
adj.get(v).add(u);
}
// A utility function to print representation of graph
static void printGraph(ArrayList<ArrayList<Integer>> adj) {
for(int i = 0; i < adj.size(); i++) {
System.out.println("\nAdjacency linkedList.list of vertex " + i);
System.out.print("head");
for(int j = 0; j < adj.get(i).size(); j++)
System.out.print(" -> " + adj.get(i).get(j));
System.out.println();
}
}
// Driver Code
public static void main(String[] args) {
// Creating a graph with 5 vertices
int vertices = 5;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>(vertices);
for(int i = 0; i < vertices; i++)
adj.add(new ArrayList<>());
// Adding edges one by one
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
printGraph(adj);
}
}