File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -30,15 +30,49 @@ class Graph {
30
30
console . log ( i + ' -> ' + vertex )
31
31
}
32
32
}
33
+
34
+ /**
35
+ * Prints the Breadth first traversal of the graph from source.
36
+ *
37
+ * @param {number } source The source vertex to start BFS.
38
+ */
39
+ bfs ( source ) {
40
+ const queue = [ ]
41
+ const visited = new Set ( )
42
+ queue . unshift ( [ source , 0 ] ) // level of source is 0
43
+ visited . add ( source )
44
+ while ( queue . length ) {
45
+ const front = queue [ 0 ]
46
+ const node = front [ 0 ]
47
+ const level = front [ 1 ]
48
+ queue . shift ( ) // remove the front of the queue
49
+ console . log ( `Visited node ${ node } at level ${ level } .` )
50
+ for ( const next of this . adjacencyMap [ node ] ) {
51
+ if ( ! visited . has ( next ) ) { // not visited
52
+ queue . unshift ( [ next , level + 1 ] ) // level 1 more than current
53
+ visited . add ( next )
54
+ }
55
+ }
56
+ }
57
+ }
33
58
}
34
59
35
60
const example = ( ) => {
36
61
const g = new Graph ( )
37
62
g . addVertex ( 1 )
38
63
g . addVertex ( 2 )
39
64
g . addVertex ( 3 )
65
+ g . addVertex ( 4 )
66
+ g . addVertex ( 5 )
40
67
g . addEdge ( 1 , 2 )
41
68
g . addEdge ( 1 , 3 )
69
+ g . addEdge ( 2 , 4 )
70
+ g . addEdge ( 2 , 5 )
71
+ console . log ( 'Printing the adjacency list:\n' )
42
72
g . printGraph ( )
73
+
74
+ // perform a breadth first search
75
+ console . log ( '\nBreadth first search at node 1:\n' )
76
+ g . bfs ( 1 )
43
77
}
44
78
example ( )
You can’t perform that action at this time.
0 commit comments