File tree Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Expand file tree Collapse file tree 1 file changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+
3
+ class GraphBFS {
4
+
5
+ Map <Object ,ArrayList <Object >> map ;
6
+
7
+ GraphBFS (){
8
+ this .map = new HashMap <>();
9
+ }
10
+
11
+ public void add_edge (Object v1 , Object v2 ) {
12
+
13
+ ArrayList <Object > list ;
14
+
15
+ if (map .containsKey (v1 ))
16
+ list = map .get (v1 );
17
+ else
18
+ list = new ArrayList <>();
19
+ list .add (v2 );
20
+ this .map .put (v1 , list );
21
+
22
+ if (map .containsKey (v2 ))
23
+ list = map .get (v2 );
24
+ else
25
+ list = new ArrayList <>();
26
+ list .add (v1 );
27
+ this .map .put (v2 , list );
28
+ }
29
+
30
+ public void bfs (Object src ) {
31
+ Queue <Object > q = new LinkedList <>();
32
+ Map <Object ,Boolean > visited = new HashMap <>();
33
+
34
+ q .add (src );
35
+ visited .put (src , true );
36
+
37
+
38
+ while (!q .isEmpty ()) {
39
+ //System.out.println(q);
40
+ Object curr_item = q .remove ();
41
+ System .out .println (curr_item );
42
+
43
+ ArrayList <Object > list = this .map .get (curr_item );
44
+
45
+ for (Object o : list ) {
46
+ if (!visited .containsKey (o ) || !visited .get (o )) {
47
+ q .add (o );
48
+ visited .put (o , true );
49
+ }
50
+ }
51
+ }
52
+
53
+ }
54
+
55
+ }
56
+
57
+ public class BFS_Traversal_Graph {
58
+
59
+ public static void main (String [] args ) {
60
+ // TODO Auto-generated method stub
61
+
62
+ GraphBFS g = new GraphBFS ();
63
+
64
+ g .add_edge (0 , 1 );
65
+ g .add_edge (0 , 3 );
66
+ g .add_edge (1 , 2 );
67
+ g .add_edge (2 , 3 );
68
+ g .add_edge (3 , 4 );
69
+ g .add_edge (4 , 5 );
70
+
71
+ g .bfs (0 );
72
+
73
+ }
74
+
75
+ }
You can’t perform that action at this time.
0 commit comments