albertorestifo / node-dijkstra

A NodeJS implementation of Dijkstra's algorithm
MIT License
158 stars 37 forks source link

Can't add a node as a neighbour of itself #12

Closed Leoooob closed 7 years ago

Leoooob commented 7 years ago

I'm using this module to work out the shortest route that goes through all nodes and came across an error when adding the paths to a node from an array. You cannot loop a node eg. ..addNode('A',{A:0, B:1})

Not a major bug, but it does throw an error. Error: Could not add node at key "item 0", make sure it's a valid node

Minimum working example:

const Graph = require('node-dijkstra')

const route = new Graph()

route.addNode('A', { A: 0, B: 1 })
route.addNode('B', { A: 1, C: 2, D: 4 })
route.addNode('C', { B: 2, D: 1 })
route.addNode('D', { C: 1, B: 4 })

route.path('A', 'D') // => ['A', 'B', 'C', 'D'] 
albertorestifo commented 7 years ago

Thanks for the report!

The issue is not with the sef-referencing points. Working example with self-referencing points.

The problem in your example is that you are trying to define a node with cost 0. In the dijkstra algorithm nodes can only have a cost greater than 0. If your cost is 0, it means those two nodes are in the same position.

Maybe throwing an error in this case can be avoided by simply ignoring the node. Regardless defining a node as it's own neighbor is not a valid graph.

Edit: What about ignoring the node and logging a warning in this scenario?