We strongly recommend to refer below post before moving on to this post.
Introduction of graphAn undirected graph:
Below is the java code of adjacency list representation of Graph
//A java code to demonstrate adjacency list representation of an undirected graph
public class GraphRepresentation {
// class to represent an adjacency list node of graph
class GraphNode {
int key;
GraphNode next;
public GraphNode(int key) {
this.key = key;
}
}
// class to represent a graph. A graph is an array of adjacency list of
// GraphNode
class Graph {
// v is number of vertex in graph
int v;
GraphNode arr[];
public Graph(int v) {
this.v = v;
arr = new GraphNode[v];
}
// add an edge in an undirected graph
public void addEdge(int i, int j) {
GraphNode node = new GraphNode(j);
node.next = this.arr[i];
this.arr[i] = node;
node = new GraphNode(i);
node.next = this.arr[j];
this.arr[j] = node;
}
// a function to print adjacency list representation of a graph
public void printGraph() {
for (int i = 0; i < this.v; i++) {
GraphNode gCrawl = this.arr[i];
System.out.print("Adjacency list of array " + i + "\nhead");
while (gCrawl != null) {
System.out.print("-->" + gCrawl.key);
gCrawl = gCrawl.next;
}
System.out.println();
}
}
}
public static void main(String[] args) {
// create a graph of which have 5 vertices.
int v = 5;
GraphRepresentation gr = new GraphRepresentation();
Graph graph = gr.new Graph(v);
// add edges of graph
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
// print adjacency list representation of above graph
graph.printGraph();
}
}
Output of above program is shown below:
Adjacency list of array 0 head-->4-->1 Adjacency list of array 1 head-->4-->2-->0 Adjacency list of array 2 head-->4-->3-->1 Adjacency list of array 3 head-->4-->2 Adjacency list of array 4 head-->3-->2-->1-->0
No comments :
Post a Comment