Skip to content

Instantly share code, notes, and snippets.

@kingster
Created November 5, 2012 11:27
Show Gist options
  • Save kingster/4016763 to your computer and use it in GitHub Desktop.
Save kingster/4016763 to your computer and use it in GitHub Desktop.
DIJKSRTRA's ALGORITHM C
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<time.h>
#include<string.h>
using namespace std;
#define IN 999
int *intrev (int *orig,unsigned short int b)
{
unsigned short int a=0;
int swap;
for(a;a<--b;a++) //increment a and decrement b until they meet eachother
{
swap=orig[a]; //put what's in a into swap space
orig[a]=orig[b]; //put what's in b into a
orig[b]=swap; //put what's in the swap (a) into b
}
return orig; //return the new (reversed) string (a pointer to it)
}
int dijsktra(int n , int **cost,int source,int target)
{
int dist[n],prev[n],i,m,min,start,d,j;
int selected[n];
for ( i = 0 ; i < n ; i++)
selected[i] = 0 ;
int path[n];
for(i=1;i< n;i++)
{
dist[i] = IN;
prev[i] = -1;
}
start = source;
selected[start]=1;
dist[start] = 0;
while(selected[target] ==0)
{
min = IN;
m = 0;
for(i=1;i< n;i++)
{
d = dist[start] +cost[start][i];
if(d< dist[i]&&selected[i]==0)
{
dist[i] = d;
prev[i] = start;
}
if(min>dist[i] && selected[i]==0)
{
min = dist[i];
m = i;
}
}
start = m;
selected[start] = 1;
}
start = target;
j = 0;
while(start != -1)
{
path[j++] = start ;// + 65;
//cout << path[j] << endl;
start = prev[start];
}
//path[j]='\0';
intrev(path, j);
for ( i = 0 ; i < j ; i++ )
cout << path[i] << " " ;
cout << endl;
return dist[target];
}
main()
{
int i,j,w,ch,co;
int **cost , n;
int source, target,x,y;
printf("Enter the No of nodes: ");
cin >> n;
cost = (int**) malloc(n*sizeof(int*));
for (int i = 0; i < n; i++)
cost[i] = (int*) malloc(n*sizeof(int));
for(i=1;i< n;i++)
for(j=1;j< n;j++)
cost[i][j] = IN;
srand(time(NULL));
for(x=1;x< n;x++)
{
for(y=x+1;y< n;y++)
{
w = rand() %10 ; // random weights. you can change as per your need.
cout << "Cost : " << x << " -> " << y << " = " << w << endl;
cost [x][y] = cost[y][x] = w;
}
}
printf("\nEnter The Source:");
cin >> source;
printf("\nEnter The Target");
cin >> target ;
printf("\nShortest Path Algorithm(DIJKSRTRA's ALGORITHM)\n");
co = dijsktra(n, cost,source,target);
printf("\nShortest Path Cost: %d ",co);
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment