File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Graph Theory/Depth First Search Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ var l = console . log ;
2
+
3
+ function DFSFindPath ( graph , srcNode , destNode ) {
4
+ var isVisited = Object . create ( null ) ,
5
+ isFound ,
6
+ dfsPath ,
7
+ nextNode ;
8
+
9
+ dfsPath = [ ] ;
10
+ dfsTraverse ( srcNode ) ;
11
+
12
+ return {
13
+ distance : isFound ? dfsPath . length - 1 : Infinity ,
14
+ path : isFound ? dfsPath : [ ]
15
+ }
16
+
17
+ function dfsTraverse ( node ) {
18
+ isVisited [ node ] = true ;
19
+ dfsPath . push ( node ) ;
20
+ isFound = node === destNode ;
21
+ if ( isFound ) return ;
22
+
23
+ for ( var i = 0 ; i < graph [ node ] . length ; i ++ ) {
24
+ nextNode = graph [ node ] [ i ] ;
25
+ if ( isVisited [ nextNode ] ) continue ;
26
+ dfsTraverse ( nextNode ) ;
27
+ if ( isFound ) return ;
28
+ }
29
+ }
30
+ }
31
+
32
+ /* TESTING */
33
+ var graph = {
34
+ 1 : [ 2 , 3 ] ,
35
+ 2 : [ 1 , 3 , 4 , 5 ] ,
36
+ 3 : [ 1 , 2 , 4 ] ,
37
+ 4 : [ 2 , 3 , 5 ] ,
38
+ 5 : [ 2 , 4 ] ,
39
+ }
40
+ var srcNode = 1 , destNode = 5 ;
41
+
42
+ console . log ( DFSFindPath ( graph , srcNode , destNode ) ) ;
You can’t perform that action at this time.
0 commit comments