@@ -20,7 +20,7 @@ const Queue = require('../queues/queue');
2020 * - Find shortest paths (between two vertices)
2121 *
2222 * https://repl.it/@amejiarosario/graphpy
23- * http://www.pythontutor.com/visualize.html#mode=edit
23+ * http://www.pythontutor.com/visualize.html#mode=edit - https://goo.gl/Xp7Zpm
2424 *
2525 */
2626class Graph {
@@ -195,38 +195,33 @@ class Graph {
195195 *
196196 * @param {any } source vertex's value
197197 * @param {any } destination vertex's value
198- * @param {Map<Node> } path current path from source to destination
198+ * @param {Map<Node> } newPath current path from source to destination
199199 * @returns list of nodes from source to destination
200200 */
201201 findPath ( source , destination , path = new Map ( ) ) {
202202 const sourceNode = this . nodes . get ( source ) ;
203203 const destinationNode = this . nodes . get ( destination ) ;
204+ const newPath = new Map ( path ) ;
204205
205206 if ( ! destinationNode || ! sourceNode ) return [ ] ;
206207
208+ newPath . set ( sourceNode ) ;
209+
207210 if ( source === destination ) {
208- return [ sourceNode ] ;
211+ return Array . from ( newPath . keys ( ) ) ;
209212 }
210213
211- path . set ( sourceNode ) ;
212-
213- const wasFound = sourceNode . getAdjacents ( ) . find ( ( node ) => {
214- if ( node === destinationNode ) {
215- path . set ( destinationNode ) ;
216- return true ;
217- }
218-
219- if ( ! path . has ( node ) ) {
220- const newPath = this . findPath ( node . value , destination , path ) ;
221- if ( newPath . length ) {
222- return true ;
214+ // eslint-disable-next-line no-restricted-syntax
215+ for ( const node of sourceNode . getAdjacents ( ) ) {
216+ if ( ! newPath . has ( node ) ) {
217+ const nextPath = this . findPath ( node . value , destination , newPath ) ;
218+ if ( nextPath . length ) {
219+ return nextPath ;
223220 }
224221 }
222+ }
225223
226- return false ;
227- } ) ;
228-
229- return wasFound ? Array . from ( path . keys ( ) ) : [ ] ;
224+ return [ ] ;
230225 }
231226
232227 // you -> mary -> barbara
0 commit comments