Monday, 17 November 2014

Dijkstra's algorithm

Dijkstra's algorithm, conceived by 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 non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.


C code:
#include<stdio.h>
min(int x,int y)
{
    if(x<y){return x;}
    else
        return y;
}

main()
{
int n;
printf("Enter the total number of nodes\n");
scanf("%d",&n);
int adj[n][n];//Adjacency Matrix
int weight[n][n];
int i,j;
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        weight[i][j]=0;
        printf("Is node %d connected to node %d",i+1,j+1);//Press 1 if yes else press 0
        scanf("%d",&adj[i][j]);
        if(adj[i][j]==1)
        {
            printf("Enter weight of %d to %d",i+1,j+1);
            scanf("%d",&weight[i][j]);
        }
    }
}
printf("Enter the starting node\n");
int start;
scanf("%d",&start);
start--;
int visit[n];
int cnt=1;
int dist[n];
for(i=0;i<n;i++)
{
    visit[i]=0;
    dist[i]=1000000;
}
visit[start]=1;
dist[start]=0;
int cur=start;
while(cnt!=n)//Will run till all the nodes are not visited
{
    int counter=0;
    for(i=0;i<n;i++)
    {
        if(adj[cur][i]==1&&!(visit[i]))
        {
            int yu=(dist[cur]+weight[cur][i]);
            dist[i]=min(dist[i],yu);
        }
    }
    int least=10000;
for(i=0;i<n;i++)
{
    if(!(visit[i]))
    {
        least=min(dist[i],least);
        if(least==dist[i])
        {
            cur=i;
        }
    }
}
visit[cur]=1;
cnt++;
}
start++;
printf("\nLengths:\n");
for(i=0;i<n;i++)
    printf("%d->%d=%d\n",start,i+1,dist[i]);

}

No comments:

Post a Comment