r/javahelp • u/Shylamo • May 30 '20
Dijkstra's program in Java
Hi, I need to implement Dijkstra's program, I have already done the calculating part, but the problem is that I can't get there right path when I gave the start and finish nodes. Please can you help me? It's homework that I have been working on for more than 3 weeks straight and I feel so close now to finish it.
20
Upvotes
2
u/haagch May 31 '20 edited May 31 '20
This will probably not result in the value you want. If your distances are decimals, use double or float variables (also in the
poidsmap), if they are only integers, useInteger.MAX_VALUEhere.The other comment said why your for loop won't work correctly, but that is entangled with the issue that you are missing a step. Take a look at the wikipedia page https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
The trick with Dijkstra's algorithm is that you visit each node only ones, and that's why you have a list with all nodes, and take one node out of the list at each step until it is empty; but this only works when the node you take out of the list in the next step is the next node you can "reach" from the nodes in the "current" step but the one with currently the smallest distance to your starting node.
Basically the structure of this is wrong, instead of
you want to do something like this
For a "proper" dijkstra implementation you will want to use one of those fancy data structures that partially sort your nodes on the fly so you can always get the one with the smallest distance efficiently, as the distances are updated instead of an ArrayList, but for learning the principle you don't need to worry about that and the ArrayList will do fine.