Dijkstra's algorithm

From Rosetta Code
Dijkstra's algorithm is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
This page uses content from Wikipedia. The original article was at Dijkstra's_algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.

For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First).

Java

Notes for this solution:

  • The number of nodes is fixed to less than 50
  • At every iteration, the next minimum distance node found by linear traversal of all nodes, which is inefficient.

<lang java>import java.io.*; import java.util.*;

class Graph {

   private static final int MAXNODES = 50;
   private static final int INFINITY = Integer.MAX_VALUE;
   int n;
   int[][] weight = new int[MAXNODES][MAXNODES];
   int[] distance = new int[MAXNODES];
   int[] precede = new int[MAXNODES];
   /**
    * Find the shortest path across the graph using Dijkstra's algorithm.
    */
   void buildSpanningTree(int source, int destination) {

boolean[] visit = new boolean[MAXNODES];

for (int i=0 ; i<n ; i++) { distance[i] = INFINITY; precede[i] = INFINITY; } distance[source] = 0;

int current = source; while (current != destination) { int distcurr = distance[current]; int smalldist = INFINITY; int k = -1; visit[current] = true;

for (int i=0; i<n; i++) { if (visit[i]) continue;

int newdist = distcurr + weight[current][i]; if (newdist < distance[i]) { distance[i] = newdist; precede[i] = current; } if (distance[i] < smalldist) { smalldist = distance[i]; k = i; } } current = k; }

   }
   /**
    * Get the shortest path across a tree that has had its path weights
    * calculated.
    */
   int[] getShortestPath(int source, int destination) {

int i = destination; int finall = 0; int[] path = new int[MAXNODES];

path[finall] = destination; finall++; while (precede[i] != source) { int j = precede[i];

i = j; path[finall] = i; finall++; } path[finall] = source;

int[] result = new int[finall+1]; System.arraycopy(path, 0, result, 0, finall+1); return result;

   }
   /**
    * Print the result.
    */
   void displayResult(int[] path) {

System.out.println("\nThe shortest path followed is : \n"); for (int i = path.length-1 ; i>0 ; i--) System.out.println("\t\t( " + path[i] + " ->" + path[i-1] + " ) with cost = " + weight[path[i]][path[i-1]]); System.out.println("For the Total Cost = " + distance[path[path.length-1]]);

   }
   /**
    * Prompt for a number.
    */
   int getNumber(String msg) {

int ne = 0; BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

try { System.out.print("\n" + msg + " : "); ne = Integer.parseInt(in.readLine()); } catch (Exception e) { System.out.println("I/O Error"); } return ne;

   }
   /**
    * Prompt for a tree, build and display a path across it.
    */
   void SPA() {

n = getNumber("Enter the number of nodes (Less than " + MAXNODES + ") in the matrix");

System.out.print("\nEnter the cost matrix : \n\n"); for (int i=0 ; i<n ; i++) for (int j=0 ; j<n ; j++) weight[i][j] = getNumber("Cost " + (i+1) + "--" + (j+1));

int s = getNumber("Enter the source node"); int d = getNumber("Enter the destination node");

buildSpanningTree(s, d); displayResult(getShortestPath(s, d));

   }

}

public class Dijkstra {

   public static void main(String args[]) {

Graph g = new Graph(); g.SPA();

   }

}</lang>