File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .LinkedList ;
2+ import java .util .Queue ;
3+
4+ public class AdjListGraph {
5+ // Undirected graph implementation using list.
6+
7+ private LinkedList <Integer >[ ] adj ;
8+ private int V ; // number of vertices
9+ private int E ; // number of edges
10+
11+ public AdjListGraph (int nodes ) {
12+ this .V = nodes ;
13+ this .E = 0 ;
14+ this .adj = new LinkedList [nodes ];
15+ for (int v = 0 ; v < V ; v ++) {
16+ adj [v ] = new LinkedList <>();
17+ }
18+ }
19+
20+ public void addEdge (int u , int v ) {
21+ adj [u ].add (v );
22+ adj [v ].add (u );
23+ E ++;
24+ }
25+
26+ public String toString () {
27+ StringBuilder sb = new StringBuilder ();
28+ sb .append (V + " vertices, " + E + " edges " + "\n " );
29+ for (int v = 0 ; v < V ; v ++) {
30+ sb .append (v + ": " );
31+ for (int w : adj [v ]) {
32+ sb .append (w + " " );
33+ }
34+ sb .append ("\n " );
35+ }
36+ return sb .toString ();
37+ }
38+ public void bfs (int s ){
39+ boolean []visited =new boolean [V ];
40+ Queue <Integer >q =new LinkedList <>();
41+ visited [s ]=true ;
42+ q .offer (s );
43+ while (!q .isEmpty ()){
44+ int u =q .poll ();
45+ System .out .print (u +" " );
46+ for (int v :adj [u ]){
47+ if (!visited [v ]){
48+ visited [v ]=true ;
49+ q .offer (v );
50+ }
51+ }
52+ }
53+ }
54+
55+ public static void main (String [] args ) {
56+ AdjListGraph g = new AdjListGraph (5 );
57+ g .addEdge (0 , 1 );
58+ g .addEdge (1 , 2 );
59+ g .addEdge (2 , 3 );
60+ g .addEdge (3 , 0 );
61+ // 4
62+ g .bfs (0 );
63+
64+
65+ }
66+ }
You can’t perform that action at this time.
0 commit comments