0

I'm trying to create an implementation of Dijkstra's pathfinding which seems to be working great, apart from if I ask it to create a route that starts and ends in the same place.

JSFiddle: http://jsfiddle.net/Lt6b4ecr/

I need it to pick the lowest possible weighted route which should be B-C-E-B but instead it just sits at 0 :(

My graph is designed as so:

var graph = {
    A: { B: '5', D: '5', E: '7' },
    B: { C: '4' },
    C: { D: '8', E: '2' },
    D: { C: '8', E: '6' },
    E: { B: '3' }};

and worth noting that the connections/edges are to be treated as one way only.

Any help would be massively appreciated!

c0der
  • 18,467
  • 6
  • 33
  • 65
antonmills
  • 171
  • 2
  • 15

2 Answers2

1

The result that you get is correct. An empty path is a valid path.

Simone
  • 2,261
  • 2
  • 19
  • 27
0

The result you are getting is correct, since an empty path is always shorter (assuming all distances are non-negative) than a non-empty path!

I found your code incredibly hard to debug (try to keep functions MUCH shorter, so each only does one clear job!) but as a starting point I found that your algorithm actually does something like:

B -> B (distance 0)

B -> B -> C (distance 4)

B -> B -> C -> E (distance 6)

"Cannot find a route back to B, as it's already been used"

...

B -> B (distance 0) was the shortest

So essentially, in order to get the result you desire, you just need to stop the algorithm from creating a path from the start point to itself. However, if this code is ever going to get reviewed for how well written it is, or re-used in the future, I'd suggest re-factoring it heavily!

Tom Lord
  • 27,404
  • 4
  • 50
  • 77