File tree Expand file tree Collapse file tree 1 file changed +9
-11
lines changed Expand file tree Collapse file tree 1 file changed +9
-11
lines changed Original file line number Diff line number Diff line change @@ -39,21 +39,19 @@ class Graph {
3939 * @param {number } source The source vertex to start BFS.
4040 */
4141 bfs ( source , output = value => console . log ( value ) ) {
42- const queue = [ ]
42+ const queue = [ [ source , 0 ] ] // level of source is 0
4343 const visited = new Set ( )
44- queue . unshift ( [ source , 0 ] ) // level of source is 0
45- visited . add ( source )
44+
4645 while ( queue . length ) {
47- const front = queue [ 0 ]
48- const node = front [ 0 ]
49- const level = front [ 1 ]
50- queue . shift ( ) // remove the front of the queue
46+ const [ node , level ] = queue . shift ( ) // remove the front of the queue
47+ if ( visited . has ( node ) ) { // visited
48+ continue
49+ }
50+
51+ visited . add ( node )
5152 output ( `Visited node ${ node } at level ${ level } .` )
5253 for ( const next of this . adjacencyMap [ node ] ) {
53- if ( ! visited . has ( next ) ) { // not visited
54- queue . unshift ( [ next , level + 1 ] ) // level 1 more than current
55- visited . add ( next )
56- }
54+ queue . push ( [ next , level + 1 ] ) // level 1 more than current
5755 }
5856 }
5957 }
You can’t perform that action at this time.
0 commit comments