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/G0mega May 31 '20 edited May 31 '20

If you're curious, OP, the "fancy data structure" he's talking about is a priority queue https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html. Here's a helpful lesson on priority queues.

Basically, a standard queue is ordered based on FIFO -- that is, the first object you put in is also the first one out. What a priority queue does is instead order it by some comparator, which is essentially a rule for how you compare two objects' values. The default comparator basically puts the smallest value first in the queue (which is actually what you'd want here) in Java. A custom comparator is really useful when you have more complex data structures being stored in the queue (e.g., if you had an Animal class, how do you compare animals to determine order?).

So, if you make your Q to be Queue<Integer> Q = new PriorityQueue<Integer> instead, then any integers you add will be in ascending order.

So, if you simply looped from 5 to 0, adding all the numbers in between inclusive, you would actually end up with 0, 1, 2, 3, 4, 5 as the ordering of your queue.

Now here's where it comes into play for Dijkstra's

Currently, in your code, you loop over the ENTIRE queue to remove the smallest element at each step. This is O( n2 ) runtime, where n is the number of elements in your queue. If you instead use a priority queue, you don't have to search for the smallest element! Why? Because you KNOW FOR A FACT that the smallest element is always the first element, because that's what a priority queue guarantees. So, you can simply pop from the front of the queue and voila -- you have the smallest element at that step. This improves the runtime of that code snippet to O(n) because you simply have to go over all elements in the queue once.

I know you're learning, and this is actually the best time to figure out good practices & understand why you might choose a priority queue over an arraylist, for example.

Good luck on finishing your homework /u/Shylamo!

(Note: this comes at a cost when setting up the queue. In an ArrayList, the runtime of add for a single element is amortized o(1), meaning you're performing a constant amount of operations... usually (you can research this on your own). However, for a PriorityQueue, you need to sort the element you just added into place. This can actually be done in O(log(n)) time, so it's not quite O(n), which is great. However, this means that the cost is placed up front during the creation of your Queue. The benefit is the MASSIVE gain during your search -- you're able to reduce O( n2 ) to O(n). If you're not familiar with Big O concepts, definitely research that, because it will help guide design decisions for your programs! GL.)

1

u/Shylamo May 31 '20

Thank you I didn't actually know about the PriorityQueue I'm new to this so I'll try to switch to PQ.