Skip to main content

Dijkstra's algorithm

Djikstra's algorithm 

  •  solves the problem of finding the shortest path from a point in a graph (the source) to a destination. It turns out that one can find the shortest paths from a given source to all points in a graph in the same time, hence this problem is sometimes called the single-source shortest paths problem.
  • This problem is related to the spanning tree one. The graph representing all the paths from one vertex to all the others must be a spanning tree - it must include all vertices. There will also be no cycles as a cycle would define more than one path from the selected vertex to at least one other vertex. For a graph,

G = (V,E)where
  • V is a set of vertices and
  • E is a set of edges.

Dijkstra's algorithm keeps two sets of vertices:
S  the set of vertices whose shortest paths from the source have already been determined and
V-   S : 
 the remaining vertices.
The other data structures needed are:
d :array of best estimates of shortest path to each vertex
pi :an array of predecessors for each vertex
The basic mode of operation is:
  1. Initialise d and pi,
  2. Set S to empty,
  3. While there are still vertices in V-S,
    1. Sort the vertices in V-S according to the current best estimate of their distance from the source,
    2. Add u, the closest vertex in V-S, to S,
    3. Relax all the vertices still in V-S connected to u
The  Algorithm is :
shortest_paths( Graph g, Node s )
    initialise_single_source( g, s )
    S := { 0 }        /* Make S empty */
    Q := Vertices( g ) /* Put the vertices in a PQ */
    while not Empty(Q) 
        u := ExtractCheapest( Q );
        AddNode( S, u ); /* Add u to S */
        for each vertex v in Adjacent( u )
            relax( u, v, w )


initialise_single_source( Graph g, Node s )
   for each vertex v in Vertices( g )
       g.d[v] := infinity
       g.pi[v] := nil
   g.d[s] := 0;

relax( Node u, Node v, double w[][] )
    if d[v] > d[u] + w[u,v] then
       d[v] := d[u] + w[u,v]
       pi[v] := u

Example

Given the following directed graph
images/lecture21/BellFordexample.png
Using vertex 5 as the source (setting its distance to 0), we initialize all the other distances to ∞.
images/lecture21/BellFordexample1.png
Iteration 1: Edges (u5,u2) and (u5,u4) relax updating the distances to 2 and 4
images/lecture21/BellFordexample2.png
Iteration 2: Edges (u2,u1), (u4,u2) and (u4,u3) relax updating the distances to 1, 2, and 4 respectively. Note edge (u4,u2) finds a shorter path to vertex 2 by going through vertex 4
images/lecture21/BellFordexample3.png
Iteration 3: Edge (u2,u1) relaxes (since a shorter path to vertex 2 was found in the previous iteration) updating the distance to 1
images/lecture21/BellFordexample4.png
Iteration 4: No edges relax
images/lecture21/BellFordexample5.png
The final shortest paths from vertex 5 with corresponding distances is
images/lecture21/BellFordexample6.png

CODE :-


#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<stdbool.h>
struct vertex
{
int verName;
int d;
int pi;
bool isAvailable;
struct vertex *next;
}*headVertex=NULL;

int n;
int count;
addVer(int i,int flag)
{
struct vertex *ref;
ref=(struct vertex *)malloc(sizeof(struct vertex *));
ref->verName=i;
if(flag==0)
    {
        ref->d=INT_MAX;
    }
    else
    {
        ref->d=0;
    }
ref->pi=-1;
ref->isAvailable=true;
ref->next=NULL;
ref->next=headVertex;
headVertex=ref;
}
void printVer()
{
struct vertex *ref;
ref=headVertex;
while(ref!=NULL)
{
    printf("ver:%d \t dvalue: %d \t pivalue=%d \t isAvialble=%d\n",ref->verName,ref->d,ref->pi,ref->isAvailable);
ref=ref->next;
}
}
void addEdge(int graph[n][n])
{
int start,end,weight;
printf("START VER:");
scanf("%d",&start);
printf("END VER:");
scanf("%d",&end);
printf("WEIGHT:");
scanf("%d",&weight);
graph[start][end]=weight;
}
struct vertex * findMinVer()
{
    struct vertex *ref;
    ref=headVertex;
    int min=INT_MAX;
    struct vertex *minVer;
    minVer=headVertex;
    while(ref!=NULL)
    {
        if((ref->d <= min )&& ref->isAvailable==true)
        {
            minVer=ref;
            min=minVer->d;
        }
        ref=ref->next;
    }
    minVer->isAvailable=false;
   // printf("MIN VER:%d\n",minVer->verName);
    count--;
    return minVer;
}
struct vertex * findVer(int nm)
{
    struct vertex *ref=headVertex;
    while(ref!=NULL)
    {
        if(ref->verName==nm)
        {
            break;
        }
        ref=ref->next;
    }
    return ref;
}
void relax(struct vertex * u,struct vertex *v,int weight)
{
    if(v->d >(u->d)+weight)
    {
        v->d=u->d+weight;
        v->pi=u->verName;
    }
}
void findSssp(int graph[n][n],int src)
{
    int i,j=0;
    struct vertex * veru;
    veru=headVertex;
    struct vertex *q[n];
    while(count>0)
    {
       veru=findMinVer();
      // printVer();
       //printf("%d ",veru->verName);
       j=0;
       for (i=veru->verName;j<n;j++)
       {
            if(graph[i][j]>0)
            {
              //  printf("\tGRAPH[%d][%d]: %d\t",i,j,graph[i][j]);
                relax(veru,findVer(j),graph[i][j]);
            }

       }
    }
}
main()
{
int i,j,choise,src;
printf("ENTER THE NO. OF VERTICES IN THE GRAPH");
scanf("%d",&n);
int graph[n][n];
printf("ENTER THE SOURCE VERTICE FOR SSSP");
scanf("%d",&src);
count=n;
for(i=0;i<n;i++)
{
    if(i==src)
        {
            addVer(i,1);
        }
        else
        {
            addVer(i,0);
        }

}
printVer();
for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            graph[i][j]=0;
        }
    }
while(1)
{
printf("\nMENU:\n1-ADD EDGE\n2-FIND SSSP\n3-EXIT\n");
scanf("%d",&choise);
switch(choise)
{
case 1:addEdge(graph);break;
case 2:findSssp(graph,src);printVer();break;
case 3:exit(0);
}
}
}

Comments

Popular Posts

Adaptive Software Development (ASD)

Adaptive Software Development (ASD) :- Adaptive Software Development(ASD) has been proposed by Jim High smith as technique for building complex software and system. ASD focus on human collaboration and team self-organization. Jim High smith defines an ASD "Life Cycle" that consist of three phases  Speculation Collaboration learning  During speculation, the project is initiated and adaptive cycle planning is conducted. Adaptive cycle planning uses project Initiation information,the customer's mission statement ,basic requirements and project constraint to define the set of release cycles that will be required for the project. Collaboration encompasses communication and team-work but it also enphasizes individualism because individual creativity plays an important role in collaborative thinking.It is all above all,a matter of trust. people working together must trust one another to comment without war help without irritation work as hard as ...

Kruskal’s Minimum Spanning Tree Algorithm & Programme

PROBLEM :                  Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds a minimum spanning tree for a connected weighted graph adding increasing cost arcs at each step. To understand Kruskal's algorithm let us consider the following example − Step 1 - Remove all loops and Parallel Edges Remove all loops and parallel edges from the given graph. In case of parallel edges, keep the one which has the least cost associated and ove all others. Step 2 - Arrange all edges in their increasing order of weight The next step is to create a set of edges and weight, and arrange them in an ascending order of weightage (cost). Step 3 - Add the edge which has the least weightage Now we start adding edges to the graph beginning from the one which has the least weight. Th...