Skip to content

Commit 0b3c709

Browse files
authored
Merge pull request #14 from afnizarnur/master
Add CoffeeScript implementation
2 parents 524c76f + 3325f0d commit 0b3c709

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

dijkstras.coffee

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
PriorityQueue = ->
2+
@_nodes = []
3+
@enqueue = (priority, key) ->
4+
@_nodes.push
5+
key : key
6+
priority : priority
7+
@sort()
8+
return
9+
@dequeue = ->
10+
@_nodes.shift().key
11+
@sort = ->
12+
@_nodes.sort = (a, b) ->
13+
a.priority - b.priority
14+
return
15+
@isEmpty = ->
16+
!@_nodes.length
17+
return
18+
19+
Graph = ->
20+
INFINITY = 1 / 0
21+
@vertices = {}
22+
@addVertex = (name, edges) ->
23+
@vertices[name] = edges
24+
return
25+
@shortestPath = (start, finish) ->
26+
nodes = new PriorityQueue
27+
distances = {}
28+
previous = {}
29+
path = []
30+
smallest = undefined
31+
vertex = undefined
32+
neighbor = undefined
33+
alt = undefined
34+
35+
for vertex of @vertices
36+
if vertex is start
37+
distances[vertex] = 0
38+
nodes.enqueue(0, vertex)
39+
else
40+
distances[vertex] = INFINITY
41+
nodes.enqueue(INFINITY, vertex)
42+
previous[vertex] = null
43+
44+
while not nodes.isEmpty()
45+
smallest = nodes.dequeue()
46+
47+
if smallest is finish
48+
path = []
49+
while previous[smallest]
50+
path.push smallest
51+
smallest = previous[smallest]
52+
break
53+
54+
if not smallest or distances[smallest] is INFINITY
55+
continue
56+
for neighbor of @vertices[smallest]
57+
alt = distances[smallest] + @vertices[smallest][neighbor]
58+
if alt < distances[neighbor]
59+
distances[neighbor] = alt
60+
previous[neighbor] = smallest
61+
nodes.enqueue alt, neighbor
62+
path
63+
return
64+
65+
g = new Graph()
66+
67+
g.addVertex 'A',
68+
B: 7
69+
C: 8
70+
g.addVertex 'B',
71+
A: 7
72+
F: 2
73+
g.addVertex 'C',
74+
A: 8
75+
F: 6
76+
G: 4
77+
g.addVertex 'D', F: 8
78+
g.addVertex 'E', H: 1
79+
g.addVertex 'F',
80+
B: 2
81+
C: 6
82+
D: 8
83+
G: 9
84+
H: 3
85+
g.addVertex 'G',
86+
C: 4
87+
F: 9
88+
g.addVertex 'H',
89+
E: 1
90+
F: 3
91+
92+
console.log g.shortestPath('A', 'H').concat(['A']).reverse()

0 commit comments

Comments
 (0)