Sunday 6 October 2013

Implementation of Dijkstra, single source shortest path.

/*
ALGORITHM
=========
1.      Initialize distance of each vertex from source as INF, and distance back to source = 0.
2.      For I = 0 to Total vertices Repeat step 3 to 4.
3.      Find minimum distance vertex, which is not yet explored and put it to explored set.
4.      Find all vertices reachable from current vertex and update its distance if it is less than distance[currentVertex] + edge weight.

COMPLEXITY
==========
Time  : O(|V||E|) .

Time complexity can be improved by using Fibonacci heap to retrieve minimum value.
Time : O(|E| + |V|log|V|).

LIMITATIONS
===========
•      Dijkstra algorithm can be used for graphs with all positive weight edges only. 
•      Dijkstra is not lacks distribute property.
*/
 
public int minimum(int distance[],boolean visited[]) {
      int min = INF,minNode = -1;
      int i;
      for(i=0; i<totalVertices; i++) {
            if(distance[i] <= min && visited[i] == false) {
                  min = distance[i];
                  minNode = i;
            }
      }
      return minNode;
}

public void dijkstra(int sourceVertex) {
      System.out.println("nnDIJKSTRA");
      int i,j,minV,cost;
      Vertex minVertex,target;
      
      //Distance array to store distance of each vertex from sourcevertex
      int distance[] = new int[totalVertices];
      boolean visited[] = new boolean[totalVertices];
      
      //Initialize distance array with INF, and distance[source] = 0.
      for(i=0; i<totalVertices; i++) {
            visited[i] = false;
            distance[i] = INF;
      }
      distance[sourceVertex] = 0;
      
      for(i=0; i<totalVertices; i++) {
            //Get minimum vertex out of all unexplored vertex 
//and put it to explored set.
            minV = minimum(distance,visited);
            visited[minV] = true;
            if(distance[minV] == INF)
                  continue;
            minVertex = vertices[minV];

            //compute the distance, if it is less than current distance then update it.
            for(j=0; j<minVertex.edges.size(); j++) {
                  cost = distance[minV] + minVertex.edges.get(j).weight;
                  target = minVertex.edges.get(j).Target;
                  if(cost < distance[target.vertexId]) {
                        distance[target.vertexId] =  cost;
                  }
            }
      }
            
}
      



No comments:

Post a Comment