@@ -7,7 +7,7 @@ class Node {
77 constructor ( data ) {
88 this . data = data ;
99 this . adjacents = [ ] ;
10- this . visited = false ;
10+ this . metadata = { } ;
1111 }
1212
1313 get left ( ) {
@@ -76,6 +76,7 @@ class Graph {
7676 targetNode = this . getNode ( target ) ;
7777
7878 sourceNode . adjacents . push ( targetNode ) ;
79+
7980 this . nodes . set ( sourceNode . data , sourceNode ) ;
8081 this . nodes . set ( targetNode . data , targetNode ) ;
8182
@@ -125,30 +126,40 @@ function isNode(thing){
125126
126127Graph . prototype . bfs = bfs ;
127128
129+ /**
130+ * Set all visited nodes to false
131+ */
132+ Graph . prototype . clearVisitedNodes = function ( ) {
133+ this . nodes . forEach ( function ( node ) {
134+ node . metadata . visited = false ;
135+ } ) ;
136+ } ;
137+
128138/**
129139 * Breadth-first search
130140 *
131141 * O(n)
132142 *
133143 * @param start data or node reference
134144 */
135- function * bfs ( start ) {
145+ function * bfs ( start , clearVisited = true ) {
136146 const queue = new Queue ( ) ;
137147
138148 queue . add ( this . getNode ( start ) ) ;
139149
140- this . nodes . forEach ( function ( node ) {
141- node . visited = false ;
142- } ) ;
150+ if ( clearVisited ) {
151+ this . clearVisitedNodes ( ) ;
152+ }
143153
144154 while ( ! queue . isEmpty ( ) ) {
145155 const node = queue . remove ( ) ;
146- node . visited = true ;
156+ node . metadata . visited = true ;
157+
147158 yield node ;
148159
149160 const adjacents = node . adjacents || [ ] ;
150161 adjacents . forEach ( function ( adjacent ) {
151- if ( ! adjacent . visited ) {
162+ if ( ! adjacent . metadata . visited ) {
152163 queue . add ( adjacent ) ;
153164 }
154165 } ) ;
0 commit comments