Friday, 2 May 2014

Dijkstra algorithm

Implement Dijkstra’s Algorithm

Input:
The first line contains the number of vertices (V in number) and number of edges (E in number) separated by a space.  E lines will follow, each containing 3 integers in the following format:
v1 v2 d
where, v1 and v2 are the two vertices having an undirected edge of length ‘d’ between them. The vertex numbers will range from 0 to V-1.

Output:
A list of integers separated by spaces where the ith integer will denote the shortest distance of ith vertex from source. Note that indexing starts from 0 and 0 <= i < V.

Constraints: 
1<=V<=100
1<=E<=100
1<=d<=100





#include <stdio.h>
#include <limits.h>
#include<stdlib.h>
void printSolution(int dist[], int V)
{
 int i=0;
 for ( i = 0; i < V-1; i++)
    printf("%d ",dist[i]);
    printf("%d",dist[V-1]);
}
void SSSP(int **gr, int s,int V)
{
    int dist[V],i,j,k;
    for (i = 0; i < V; i++)
    {
      for (j = 0; j < V; j++)
   {
          if(gr[i][j]>100 || gr[i][j]<1)
          gr[i][j]=9999;
          }
    }
    for (i = 0; i < V; i++)
    {
      for (j = 0; j < V; j++)
   {
          for (k = 0; k < V; k++)
  {
                if (gr[j][k] > gr[j][i] + gr[i][k])
      {
                   gr[j][k] = gr[j][i] + gr[i][k];
                   }
                }
          }
    }
    gr[s][s]=0;
    for (i = 0; i < V; i++)
    {
     dist[i]=gr[i][s];
    }
    printSolution(dist,V);
}
int main()
{
    int V,E;
    int **graph;
    // The vertices are numbered from 0 to V-1
    scanf("%d %d",&V,&E);
    graph = (int **)malloc(sizeof(int *)*V);
    int i=0;
    for(i=0;i<V;i++)
    graph[i] = (int *)malloc(sizeof(int)*V);
    for(i=0;i<E;i++)
    {
        int s,d,w;
        scanf("%d%d%d",&s,&d,&w);
        graph[s][d] = w;
        graph[d][s] = w;
    }
    SSSP(graph, 0,V);
  return 0;
}

No comments: