here is only basic implementation of problems for beginners. If you have any problem with any solution or any basic concept of programming or you want more efficient solution you can mail me.
my suggestion is not to copy and paste codes from here try to understand the logic and think why you were not able to solve it.

Sunday, 28 September 2014

Dijkstra’s algorithm using adjacency matrix

this program finds distance of all vertexes from a given source vertex
time complexity using adjacency matrix is O(v^2)
it doesn't work for negative weighted graphs


#include <stdio.h>
#include <limits.h>
int n;
int takemin(int dist[],int visited[]){
   int min=INT_MAX,min_index,i;
  for(i=0;i<n;i++)
     if(visited[i]==0 && dist[i] <= min){
      min=dist[i];
min_index=i;
     }
  return min_index;
}

int printfinal(int dist[],int n){
int i;
   printf("Vertex   Distance from Source\n");
   for(i=0;i<n;i++)
      printf("%d                 %d\n",i,dist[i]);
}

void dijkstra(int graph[n][n], int source){
     int dist[n],visited[n],i,j,u;
     for(i=0;i<n;i++){
      dist[i]=INT_MAX;
visited[i]=0;
     }
     //taking distance of source as 0
    dist[source]=0;
    for(j=0;j<n-1;j++){
       //take min distance vertex which is not taken yet
       u=takemin(dist,visited);
  //mark the picked vertex as visited
       visited[u]=1;
//update the distances of vertexes adjacent to the picked vertex
       for(i=0;i<n;i++){
        if(graph[u][i]>0 && visited[i]==0){
        if(dist[u]+graph[u][i]<dist[i] || dist[i]==INT_MAX){
        dist[i]=dist[u]+graph[u][i];
        }
        }
    }
    }
    printfinal(dist,n);
}

int main(){
int i,j;
printf("Enter no of vertexes\n");
scanf("%d",&n);
int graph[n][n];
printf("Enter adjacency matrix\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&graph[i][j]);
}
}
  dijkstra(graph, 0);
  return 0;
}

No comments:

Post a Comment