So I have just come across Dijkstra's algorithm for path finding and decided to try it out in C. I wrote the code to take the data of a Dijkstra diagram and find the shortest path. The data I used was:
Number of nodes: 5
Cost matrix
0 4 0 8 0
4 0 3 0 0
0 3 0 4 0
8 0 4 0 7
0 0 0 7 0
Node to visit: 5
Number of paths: 2
Path matrix
1 2 3 4 5
1 4 5 0 0
It should output:
Minimum distance is 15
Minimum distance path: ->1 ->4 ->5
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <process.h>
int main(){
int cost[10][10], path[10][10], distance[10], column, index = 1, row, min, n, i, j, v, p;
printf("Enter number of nodes: ");
scanf(" %d", &n);
printf("\n\nEnter cost matrix: ");
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++){
scanf(" %d", &cost[i][j]);
}
printf("\n");
}
printf("\n\nEnter the node to visit: ");
scanf(" %d", &v);
printf("\nEnter the number of paths for the node: ");
scanf(" %d", &p);
printf("\n\nEnter path matrix: ");
for(i = 1; i <= p; i++){
for(j = 1; j <= n; j++){
scanf(" %d", &path[i][j]);
}
printf("\n");
} // program crashes here
for(i = 1; i <= p; i++){
distance[i] = 0;
row = 1;
for(j = 1; j <=n; j++){
if(row != v){
column = path[i][j + 1];
distance[i] = distance[i] + cost[row][column];
}
}
row = column;
}
min = distance[1];
for(i = 1; i <= p; i++){
if(distance[i] <= min ){
min = distance[i];
index = i;
}
}
printf("Minimum distance is %d\n\n", min);
printf("Minimum distance path:");
for(i = 1; i <= n; i++){
if(path[index][i] != 0){
printf(" ->%d", path[index][i]);
}
}
return 0;
}
I have been over the code many times wondering why it would crash. Any help would be much appreciated. Thanks.