Graph representations using set and hash | A Java program to demonstrate adjacency list using HashMap and TreeSet representation of graphs using sets ; TreeSet is used to get clear understand of graph . ; Adds an edge to an undirected graph ; Add an edge from src to dest into the set ; Since graph is undirected , add an edge from dest to src into the set ; A utility function to print the graph ; Searches for a given edge in the graph ; Driver code ; Create the graph given in the above figure ; Print the adjacency list representation of the above graph ; Search the given edge in the graph
import java . util . * ; class Graph { HashMap < Integer , TreeSet < Integer > > graph ; static int v ; public Graph ( ) { graph = new HashMap < > ( ) ; for ( int i = 0 ; i < v ; i ++ ) { graph . put ( i , new TreeSet < > ( ) ) ; } } public void addEdge ( int src , int dest ) { graph . get ( src ) . add ( dest ) ; graph . get ( dest ) . add ( src ) ; } public void printGraph ( ) { for ( int i = 0 ; i < v ; i ++ ) { System . out . println ( " Adjacency ▁ list ▁ of ▁ vertex ▁ " + i ) ; Iterator set = graph . get ( i ) . iterator ( ) ; while ( set . hasNext ( ) ) System . out . print ( set . next ( ) + " ▁ " ) ; System . out . println ( ) ; System . out . println ( ) ; } } public void searchEdge ( int src , int dest ) { Iterator set = graph . get ( src ) . iterator ( ) ; if ( graph . get ( src ) . contains ( dest ) ) System . out . println ( " Edge ▁ from ▁ " + src + " ▁ to ▁ " + dest + " ▁ found " ) ; else System . out . println ( " Edge ▁ from ▁ " + src + " ▁ to ▁ " + dest + " ▁ not ▁ found " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { v = 5 ; Graph graph = new Graph ( ) ; graph . addEdge ( 0 , 1 ) ; graph . addEdge ( 0 , 4 ) ; graph . addEdge ( 1 , 2 ) ; graph . addEdge ( 1 , 3 ) ; graph . addEdge ( 1 , 4 ) ; graph . addEdge ( 2 , 3 ) ; graph . addEdge ( 3 , 4 ) ; graph . printGraph ( ) ; graph . searchEdge ( 2 , 1 ) ; graph . searchEdge ( 0 , 3 ) ; } }