|
| 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 | + |
| 23 | + @addVertex = (name, edges) -> |
| 24 | + @vertices[name] = edges |
| 25 | + return |
| 26 | + |
| 27 | + @shortestPath = (start, finish) -> |
| 28 | + nodes = new PriorityQueue |
| 29 | + distances = {} |
| 30 | + previous = {} |
| 31 | + path = [] |
| 32 | + smallest = undefined |
| 33 | + vertex = undefined |
| 34 | + neighbor = undefined |
| 35 | + alt = undefined |
| 36 | + |
| 37 | + for vertex of @vertices |
| 38 | + if vertex is start |
| 39 | + distances[vertex] = 0 |
| 40 | + nodes.enqueue(0, vertex) |
| 41 | + else |
| 42 | + distances[vertex] = INFINITY |
| 43 | + nodes.enqueue(INFINITY, vertex) |
| 44 | + previous[vertex] = null |
| 45 | + |
| 46 | + while not nodes.isEmpty() |
| 47 | + smallest = nodes.dequeue() |
| 48 | + |
| 49 | + if smallest is finish |
| 50 | + path = [] |
| 51 | + while previous[smallest] |
| 52 | + path.push smallest |
| 53 | + smallest = previous[smallest] |
| 54 | + break |
| 55 | + |
| 56 | + if not smallest or distances[smallest] is INFINITY |
| 57 | + continue |
| 58 | + for neighbor of @vertices[smallest] |
| 59 | + alt = distances[smallest] + @vertices[smallest][neighbor] |
| 60 | + if alt < distances[neighbor] |
| 61 | + distances[neighbor] = alt |
| 62 | + previous[neighbor] = smallest |
| 63 | + nodes.enqueue alt, neighbor |
| 64 | + path |
| 65 | + return |
| 66 | + |
| 67 | +g = new Graph() |
| 68 | + |
| 69 | +g.addVertex 'A', |
| 70 | + B: 7 |
| 71 | + C: 8 |
| 72 | +g.addVertex 'B', |
| 73 | + A: 7 |
| 74 | + F: 2 |
| 75 | +g.addVertex 'C', |
| 76 | + A: 8 |
| 77 | + F: 6 |
| 78 | + G: 4 |
| 79 | +g.addVertex 'D', F: 8 |
| 80 | +g.addVertex 'E', H: 1 |
| 81 | +g.addVertex 'F', |
| 82 | + B: 2 |
| 83 | + C: 6 |
| 84 | + D: 8 |
| 85 | + G: 9 |
| 86 | + H: 3 |
| 87 | +g.addVertex 'G', |
| 88 | + C: 4 |
| 89 | + F: 9 |
| 90 | +g.addVertex 'H', |
| 91 | + E: 1 |
| 92 | + F: 3 |
| 93 | + |
| 94 | +console.log g.shortestPath('A', 'H').concat([ 'A' ]).reverse() |
0 commit comments