I am doing an assignment for class that is supposed to be coded a very specific way. Here is the goal:
Goal: To implement Dijkstra’s algorithm for single source shortest path problem for a given directed graph using an adjacency matrix representation of the graph.
I am using Makefile to compile the code. Input will be taken via the terminal/console ./a7 < datafile
. Here is an example of the input:
6 11 0
0 1 50
0 2 10
0 4 45
1 2 15
1 4 10
2 0 20
2 3 15
3 1 20
3 4 35
4 3 30
5 4 03
And the expected output:
0 2 10
0 3 25
0 1 45
0 4 45
0 5 INF (no path)
Here is the code:
#include <limits.h> /* for INT_MAX */
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define N 10 /* max matrix size is 10 x 10 */
#define INF INT_MAX /* infinity? */
int main(int argc, char **argv) {
void getdata(int amtrx[][N], int *sz, int *stv);
void dijkstras(int amtrx[][N], int src);
if (argc < 2) {
printf("Missing Filename.\n");
return(1);
} else if (argc > 2) {
printf("Too many arguments.\n");
return(1);
}
FILE *f = fopen(argv[1], "r");
int amtrx[N][N], *sz, *stv;
stv = malloc(sizeof(int));
sz = malloc(sizeof(int));
getdata(amtrx, sz, stv);
dijkstras(amtrx, *stv);
fclose(f);
return(0);
}
void getdata(int amtrx[][N], int *sz, int *stv) {
int i, j, nsz, nedg, fr, to, vtx, wt;
scanf("%d %d %d", &nsz, &nedg, &vtx);
for(i = 0; i < nsz; i++)
for(j = 0; j < nsz; j++)
amtrx[i][j] = INF;
for(i = 0; i < nedg; i++) {
scanf("%d %d %d", &fr, &to, &wt);
amtrx[fr][to] = wt;
amtrx[to][fr] = wt;
}
*sz = nsz;
*stv = vtx;
}
void dijkstras(int amtrx[][N], int src) {
void printpaths(int amtrx[][N]);
int mindistance(int dist[], bool sptSet[]);
int dist[N];
bool sptSet[N];
int i, count, v, u;
for (i = 0; i < N; i++)
dist[i] = INF, sptSet[i] = false;
dist[src] = 0;
for (count = 0; count < N - 1; count++) {
u = mindistance(dist, sptSet);
sptSet[u] = true;
for (v = 0; v < N; v++)
if (!sptSet[v] && amtrx[u][v] && dist[u] != INF && dist[u] + amtrx[u][v] < dist[v]) {
dist[v] = dist[u] + amtrx[u][v];
}
}
printpaths(amtrx);
}
int mindistance(int dist[], bool sptSet[]) {
int min = INF, min_index;
int v;
for (v = 0; v < N; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printpaths(int amtrx[N][N]) {
//to be written
}
So far it just runs forever and doesn't print anything. I suspect maybe an infinite loop but I can't see where it's happening. I tried to run in GDB and it just says Starting program: /a7 datafile
and goes no where. I also would like help making sure my algorithm is correct, but I can save that for another question if need be. Thanks in advance!