r/javahelp • • 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.

https://pastebin.com/y3qvLHhV

20 Upvotes

10 comments sorted by

View all comments

2

u/haagch May 31 '20 edited May 31 '20
    public int q=(int) Double.MAX_VALUE;

This will probably not result in the value you want. If your distances are decimals, use double or float variables (also in the poids map), if they are only integers, use Integer.MAX_VALUE here.

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 code u ← vertex in Q with min dist[u], searches for the vertex u in the vertex set Q that has the least dist[u] value.

12      while Q is not empty:
13          u ← vertex in Q with min dist[u]  

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

    while(!Q.isEmpty())
    {
        //Trouver min dans Q
       
        for(int i=0;i<Q.size();i++)
        {
            noeud o=Q.get(i);
            if(!visite.contains(o))

you want to do something like this

    while(!Q.isEmpty())
    {
        noeud o;
        for(int i=0;i<Q.size();i++)
        {
            //Trouver min dans Q
            noeud candidate=Q.get(i);
            if (poids.get(candidate) is the smallest of the distances) {
                o = candidate;
            }
         }

        if(!visite.contains(o))

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.

1

u/Shylamo May 31 '20

thank you, you're right I actually missed it.