File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -30,15 +30,49 @@ class Graph {
3030 console . log ( i + ' -> ' + vertex )
3131 }
3232 }
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+ }
3358}
3459
3560const example = ( ) => {
3661 const g = new Graph ( )
3762 g . addVertex ( 1 )
3863 g . addVertex ( 2 )
3964 g . addVertex ( 3 )
65+ g . addVertex ( 4 )
66+ g . addVertex ( 5 )
4067 g . addEdge ( 1 , 2 )
4168 g . addEdge ( 1 , 3 )
69+ g . addEdge ( 2 , 4 )
70+ g . addEdge ( 2 , 5 )
71+ console . log ( 'Printing the adjacency list:\n' )
4272 g . printGraph ( )
73+
74+ // perform a breadth first search
75+ console . log ( '\nBreadth first search at node 1:\n' )
76+ g . bfs ( 1 )
4377}
4478example ( )
You can’t perform that action at this time.
0 commit comments