试图在C中编写Dijkstra算法并且程序崩溃

时间:2017-02-04 18:37:31

标签: c algorithm dijkstra

所以我刚刚遇到了Dijkstra的路径搜索算法,并决定在C中尝试。我编写代码来获取Dijkstra图的数据并找到最短的路径。我使用的数据是:

节点数:5

成本矩阵

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

要访问的节点:5

路径数量:2

路径矩阵

1 2 3 4 5

1 4 5 0 0

应输出:

最小距离为15

最小距离路径: - > 1 - > 4 - > 5

以下是代码:

#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;
}

我已经多次查看代码,想知道为什么它会崩溃。任何帮助将非常感激。感谢。

0 个答案:

没有答案