Last active
September 11, 2015 16:50
-
-
Save rootAvish/c2a1afcbca5c5b4fd2a7 to your computer and use it in GitHub Desktop.
This is an implementation of dijkstra's algorithm in vanilla C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright @rootavish | |
* LICENSE: Do whatever the fuck you want to do license. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
#define N 6 | |
int visited_all(int visited[]) | |
{ | |
int i=0; | |
for(i=0; i < N ; i++) { | |
if (visited[i] == 0) | |
return 0; | |
} | |
return 1; | |
} | |
int main() | |
{ | |
int visited[N]; | |
FILE *fp = fopen("graph.txt","r"); | |
int s,graph[N][N],distance[N]; | |
int i,j, distanceu=0, u=0, alt=0; | |
if (fp == NULL) { | |
fprintf(stderr,"Could not open the input file.\n");\ | |
return 1; | |
} | |
for(i=0 ;i < N ; i++) { | |
for(j=0 ; j < N ; j++) { | |
fscanf(fp, "%d", &graph[i][j]); | |
} | |
} | |
printf("Enter the source vertex: "); | |
scanf("%d",&s); | |
s--; | |
distance[s] = 0; | |
for(i=0 ; i < N ; i++) { | |
visited[i] = 0; | |
if (i != s) | |
distance[i] = INT_MAX; | |
} | |
while (!visited_all(visited)) { | |
distanceu = INT_MAX; | |
for(i=0 ; i < N ; i++) { | |
if (visited[i] == 0) { | |
if (distance[i] <= distanceu) { | |
u = i; | |
distanceu = distance[u]; | |
} | |
} | |
} | |
visited[u] = 1; | |
for(j=0; j < N ; j++) { | |
if (j != u && graph[u][j] != -1) { | |
alt = distance[u] + graph[u][j]; | |
if (alt < distance[j]) { | |
distance[j] = alt; | |
} | |
} | |
} | |
} | |
printf("The shortest paths are:\n"); | |
for(i=0 ; i < N ; i++) { | |
if (i != s) { | |
printf("Vertex %d: %d\n",i+1, distance[i]); | |
} | |
} | |
fclose(fp); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment