Djikstra Algorithm in Java

Teja IllaTeja Illa
1 min read

Djikstra Algorithm in Java

import java.util.*;

public class Main {

  public static class Node implements Comparable<Node> {
    public int vertices;
    public int distance;

    public Node(int vertices, int distance) {
      this.vertices = vertices;
      this.distance = distance;
    }

    @Override
    public int compareTo(Node node) {
      return Integer.compare(this.distance, node.distance);
    }

  }

  public static class Graph {
    int v;
    int e;

    List<List<Node>> arrList;

    public Graph(int v, int e) {
      this.v = v;
      this.e = e;

      arrList = new ArrayList<>();

      for(int i=0; i<v; i++) {
        arrList.add(new ArrayList<>());
      }
    }

    public void addEdge(int start, Node node) {
      arrList.get(start).add(node);
    }

    public void runDjikstraAlgorithm(int source) {

      int[] distanceArray = new int[v];

      Arrays.fill(distanceArray, Integer.MAX_VALUE);
      distanceArray[source] = 0;

      PriorityQueue<Node> pq = new PriorityQueue<>();

      pq.add(new Node(source, distanceArray[source]));

      while(!pq.isEmpty()) {
        Node currNode = pq.poll();
        List<Node> adjNode = arrList.get(currNode.vertices);

        for(Node node : adjNode) {
          if(distanceArray[currNode.vertices] + node.distance < distanceArray[node.vertices]) {
            distanceArray[node.vertices] = distanceArray[currNode.vertices] + node.distance;
            pq.add(new Node(node.vertices, distanceArray[node.vertices]));
          }
        }
      }

      for(int i=0; i< v; i++) {
        System.out.println(distanceArray[i]);
      }
    }
  }

  public static void main(String[] args) {

    Graph g = new Graph(6, 9);

    g.addEdge(0, new Node(1, 5));
    g.addEdge(0, new Node(2, 2));
    g.addEdge(1, new Node(3, 4));

    g.addEdge(1, new Node(4, 2));
    g.addEdge(1, new Node(2, 1));
    g.addEdge(3, new Node(4, 6));


    g.addEdge(3, new Node(5, 3));
    g.addEdge(4, new Node(5, 1));
    g.addEdge(2, new Node(4, 7));

    g.runDjikstraAlgorithm(0);

  }
}
0
Subscribe to my newsletter

Read articles from Teja Illa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Teja Illa
Teja Illa