File tree 1 file changed +77
-0
lines changed
1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change
1
+ const graph = {
2
+ 'start' : {
3
+ 'a' : 6 ,
4
+ 'b' : 2
5
+ } ,
6
+ 'a' : {
7
+ 'finish' : 1
8
+ } ,
9
+ 'b' : {
10
+ 'a' : 3 ,
11
+ 'finish' : 5
12
+ } ,
13
+ 'finish' : { }
14
+ } ;
15
+
16
+ const costs = {
17
+ 'a' : 6 ,
18
+ 'b' : 2 ,
19
+ 'finish' : Infinity
20
+ } ;
21
+
22
+ const parents = {
23
+ 'a' : 'start' ,
24
+ 'b' : 'start' ,
25
+ 'finish' : null
26
+ } ;
27
+
28
+ const processed = [ ] ;
29
+
30
+
31
+ let node = findLowestCostNode ( costs , processed ) ;
32
+ while ( node ) {
33
+ const cost = costs [ node ] ;
34
+ const neighbors = graph [ node ] ;
35
+
36
+ for ( const [ neighbor , neighborCost ] of Object . entries ( neighbors ) ) {
37
+ const newCost = cost + neighborCost ;
38
+ if ( newCost < costs [ neighbor ] ) {
39
+ costs [ neighbor ] = newCost ;
40
+ parents [ neighbor ] = node ;
41
+ }
42
+ }
43
+ processed . push ( node ) ;
44
+ node = findLowestCostNode ( costs , processed ) ;
45
+ }
46
+
47
+
48
+ console . log ( costs [ 'finish' ] ) ;
49
+ const shortestPath = restoreShortestPath ( parents ) ;
50
+ console . log ( shortestPath . join ( ' <- ' ) ) ;
51
+
52
+
53
+ function findLowestCostNode ( costs , processed ) {
54
+ let lowestCost = Infinity ;
55
+ let lowestCostNode = null ;
56
+ for ( const [ node , cost ] of Object . entries ( costs ) ) {
57
+ if ( processed . includes ( node ) ) continue ;
58
+ if ( cost < lowestCost ) {
59
+ lowestCost = cost ;
60
+ lowestCostNode = node ;
61
+ }
62
+ }
63
+
64
+ return lowestCostNode ;
65
+ }
66
+
67
+ function restoreShortestPath ( parents ) {
68
+ let startNode = 'finish' ;
69
+ const path = [ startNode ] ;
70
+ while ( startNode !== 'start' ) {
71
+ const parent = parents [ startNode ] ;
72
+ path . push ( parent ) ;
73
+ startNode = parent ;
74
+ }
75
+
76
+ return path ;
77
+ }
You can’t perform that action at this time.
0 commit comments