Showing posts with label Dijkstra's Algorithm. Show all posts
Showing posts with label Dijkstra's Algorithm. Show all posts

Sunday, July 9, 2017

Sunday, November 29, 2015

Dijkstra's Algorithm using Fibonacci Heap Priority Queue implementation : Java

This code uses Fibonacci heap for the priority queue used which is faster than other priority queue implementations (binary heap, d-way heap or linear).

Fibonacci Heap source : graphstream-project.org

Code:

import java.util.ArrayList;
import java.util.Arrays;
import org.graphstream.algorithm.util.FibonacciHeap;

public class Dijkstras {
    class Edge{
        int to, from;
        double weight;
        
        Edge(int from, int to, double weight){
            this.to = to;
            this.from = from;
            this.weight = weight;
        }
        
        public String toString(){
            return "["+from+", "+to+" : "+weight+"]";
        }
    }
    
    private ArrayList<ArrayList<Edge>> graph;
    private int edgeTo[];
    private double distTo[];
    private boolean inQ[];
    private FibonacciHeap.Node nodeRef[];
    private int V;
    
    FibonacciHeap<Double, Integer> pq;
    
    Dijkstras(int V){
        graph = new ArrayList<>();
        graph.ensureCapacity(V);
        for(int i=0;i<V;++i)graph.add(new ArrayList<>());
        edgeTo = new int[V];
        distTo = new double[V];
        this.V = V;
    }
    
    public void addEdge(int from, int to, double weight){
        graph.get(from).add(new Edge(from, to, weight));
    }
    
    public void runDijkstra(int s){
        pq = new FibonacciHeap<>();
        inQ = new boolean[V];
        nodeRef = new FibonacciHeap.Node[V];
        
        Arrays.fill(distTo, Double.POSITIVE_INFINITY);
        distTo[s] = 0;
        
        nodeRef[s] = pq.add(0.0, s);
        inQ[s] = true;
        
        while(!pq.isEmpty()){
            int v = pq.extractMin(); 
            for(Edge e : graph.get(v)){
               relax(e);
            }
        }
    }
    
    
    public void relax(Edge e){
        if(!inQ[e.to]){
            distTo[e.to] = distTo[e.from]+e.weight;
            nodeRef[e.to] = pq.add(distTo[e.to], e.to);
            inQ[e.to] = true;
            edgeTo[e.to] = e.from;
        }else if(distTo[e.to] > distTo[e.from] + e.weight){
            distTo[e.to] = distTo[e.from] + e.weight;
            edgeTo[e.to] = e.from;
            pq.decreaseKey(nodeRef[e.to], distTo[e.to]);
        }
    }
    
    public static void main(String[] args){
        Dijkstras d = new Dijkstras(8);
        
        d.addEdge(0,1,5);   d.addEdge(3,6,9);   
        d.addEdge(0,4,9);   d.addEdge(4,5,4);
        d.addEdge(0,7,8);   d.addEdge(4,6,20);
        d.addEdge(1,2,12);  d.addEdge(4,7,5);
        d.addEdge(1,3,15);  d.addEdge(5,2,1);
        d.addEdge(1,7,4);   d.addEdge(5,6,13);
        d.addEdge(2,3,3);   d.addEdge(7,5,6);
        d.addEdge(2,6,11);  d.addEdge(7,2,7);
        
        d.runDijkstra(0);
        
        System.out.println("Results: ");
        for(int i=0;i<d.V;++i){
            System.out.println("Vertex "+i+" edgeTo["+i+"] = "+d.edgeTo[i]+" distTo["+i+"] = "+d.distTo[i]);
        }
    }
    
}

Output:

Results:
Vertex 0 edgeTo[0] = 0 distTo[0] = 0.0
Vertex 1 edgeTo[1] = 0 distTo[1] = 5.0
Vertex 2 edgeTo[2] = 5 distTo[2] = 14.0
Vertex 3 edgeTo[3] = 2 distTo[3] = 17.0
Vertex 4 edgeTo[4] = 0 distTo[4] = 9.0
Vertex 5 edgeTo[5] = 4 distTo[5] = 13.0
Vertex 6 edgeTo[6] = 2 distTo[6] = 25.0
Vertex 7 edgeTo[7] = 0 distTo[7] = 8.0

Friday, August 29, 2014

Dijkstra's Algorithm Implementation in Java

This program implements Dijkstra's algorithm for finding the shortest path to all vertices from the given source in a graph. The code is simple enough. I've added comments wherever necessary.

Graph used in this example:



Code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Node {

    boolean showMoreInfo = true;
    int distanceFromSource = 0;
    String name;
    public Map<Node, Integer> neighbors = new HashMap<>();

    Node(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Node: ").append(name).append("\n");

        sb.append("Distance from source: ").append(distanceFromSource).append("\n");

        if (showMoreInfo) {
            sb.append("Neighbor nodes: \n");
            for (Node node : neighbors.keySet()) {
                sb.append(node.name).append("  Distance: ").append(this.neighbors.get(node)).append("\n");
            }

            sb.append("\n");
        }
        return sb.toString();
    }
}

public class DijkstrasAlgorithm {
    List<Node> nodes = new ArrayList<>(); 
    
    public void drawGraph() {
        Node s = new Node("s");

        //Two immediate (reachable) neighbors of Node s
        Node t = new Node("t");
        Node y = new Node("y");
        s.neighbors.put(t, 10);
        s.neighbors.put(y, 5);

        //One of the two immediate (reachable) neighbors of Node t
        Node x = new Node("x");
        t.neighbors.put(x, 1);
        t.neighbors.put(y, 2);

        y.neighbors.put(t, 3);
        y.neighbors.put(x, 9);

        //Last Node z (immediately reachable from x and y nodes)
        Node z = new Node("z");
        x.neighbors.put(z, 4);
        y.neighbors.put(z, 2);
        z.neighbors.put(x, 6);
        z.neighbors.put(s, 7);

        //Now add these to List<Node> nodes
        nodes.add(s);
        nodes.add(t);
        nodes.add(y);
        nodes.add(x);
        nodes.add(z);
    }

    private void initializeNodes(){
        for(Node node:nodes)
            node.distanceFromSource = Integer.MAX_VALUE;
        nodes.get(0).distanceFromSource = 0;
    }
    
    private void relax(Node previous, Node next){
        if(next.distanceFromSource>previous.distanceFromSource+previous.neighbors.get(next)){
            next.distanceFromSource = previous.distanceFromSource+previous.neighbors.get(next);
        }
    }
    
    private Node getMin(List<Node> nodes){
        int min = Integer.MAX_VALUE; 
        int minIndex = -1;
        for(int i=0;i<nodes.size();++i){
            if(nodes.get(i).distanceFromSource<min){
                min = nodes.get(i).distanceFromSource; 
                minIndex = i;
            }
        }
        return nodes.get(minIndex);
    }
    
    public void dijkstra(){
        List<Node> nodesCopy = new ArrayList<>();
        nodesCopy.addAll(nodes);
        
        while(!nodesCopy.isEmpty()){
            Node min = getMin(nodesCopy);
            
            Map<Node, Integer> neighbors = min.neighbors;
            for(Map.Entry<Node, Integer> me:neighbors.entrySet()){
                relax(min, me.getKey());
            }
            nodesCopy.remove(min);
        }
    }
    
    public static void main(String[] args){
        DijkstrasAlgorithm da = new DijkstrasAlgorithm();
        da.drawGraph();
        da.initializeNodes(); 
        da.dijkstra();
        
        System.out.println(da.nodes.size());
        for(Node node:da.nodes)
            System.out.println(node);
    }
}

Output:

Node: s
Distance from source: 0
Neighbor nodes:
t  Distance: 10
y  Distance: 5


Node: t
Distance from source: 8
Neighbor nodes:
x  Distance: 1
y  Distance: 2


Node: y
Distance from source: 5
Neighbor nodes:
x  Distance: 9
t  Distance: 3
z  Distance: 2


Node: x
Distance from source: 9
Neighbor nodes:
z  Distance: 4


Node: z
Distance from source: 7
Neighbor nodes:
x  Distance: 6
s  Distance: 7