0

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.

  • 1
    What's the error message? – Georg Schölly Feb 04 '17 at 18:39
  • have you tried compiling with debug symbols and running it in a debugger? – David Hoelzer Feb 04 '17 at 18:41
  • What does your debugger tell you ? You dont have a debugger ? Get one. Really. You have one but you don't know how to use it ? Start learning now. Yes, right now, it's the perfect moment to start. – Jabberwocky Feb 04 '17 at 18:45
  • I ran the code with the debug option and after it returned a signal: Program received signal SIGSEGV, Segmentation fault. – Cuan Clifford Feb 04 '17 at 18:57
  • 1
    Why are you running your loops (and array indexing) from `1`? That's a good recipe for breaking array bounds. How many nodes are you entering? If it's `10` then disaster beckons. It could be worse too when you index with `[j + 1];` – Weather Vane Feb 04 '17 at 19:10

0 Answers0