繁体   English   中英

贝尔曼福特图算法

[英]Bellman Ford graph algorithm

我有一个作业来实现贝尔曼福特的算法并在一些图表上对其进行测试。 我实现了该算法,在 3 个图表中的 2 个上对其进行了测试,并且它可以工作。 但是在第三张图上,我在调用 function 时没有 output。

Graph* temaTrecuta = createGraph(10, 12);
addOrientedEdge(temaTrecuta, 0, 0, 1, 5);
addOrientedEdge(temaTrecuta, 1, 1, 2, 3);
addOrientedEdge(temaTrecuta, 2, 2, 3, 5);
addOrientedEdge(temaTrecuta, 4, 3, 9, 5);
addOrientedEdge(temaTrecuta, 5, 1, 9, 1);
addOrientedEdge(temaTrecuta, 6, 3, 4, 1);
addOrientedEdge(temaTrecuta, 7, 4, 8, 5);
addOrientedEdge(temaTrecuta, 8, 8, 7, 1);
addOrientedEdge(temaTrecuta, 9, 7, 5, 1);
addOrientedEdge(temaTrecuta, 10, 7, 6, 3);
addOrientedEdge(temaTrecuta, 11, 6, 0, 1);

这部分创建图形及其边缘。 createGraph function 将顶点和边的数量作为参数。

void addOrientedEdge(Graph* graph, int index, int source, int destination, int cost) {
    graph->edge[index].src = source;
    graph->edge[index].dest = destination;
    graph->edge[index].cost = cost;

    graph->matrix[source][destination] = cost;
}

这是增加了新边缘的 function。

下面是我对贝尔曼福特算法的实现。

void bellmanFord(Graph* gr, int src) {
    int* dist = (int*)malloc(sizeof(int) * gr->V);
    int* path = (int*)malloc(sizeof(int) * gr->V);

    if (!path || !dist) {
        printf("Nu am putut aloca.\n");
        exit(1);
    }

    for (int i = 0; i < gr->V; ++i) {
        dist[i] = INT_MAX;
        path[i] = 0;
    }

    path[src] = -1;

    dist[src] = 0;

    for (int i = 1; i <= gr->V - 1; ++i) {
        for (int j = 0; j < gr->E; ++j) {
            int m = gr->edge[j].src;
            int n = gr->edge[j].dest;
            int cost = gr->edge[j].cost;

            if (dist[m] != INT_MAX && dist[m] + cost < dist[n]) {
                dist[n] = dist[m] + cost;
                path[n] = m; 
            }
        }
    }

    for (int i = 0; i < gr->E; ++i) {
        int m = gr->edge[i].src;
        int n = gr->edge[i].dest;
        int cost = gr->edge[i].cost;

        if (dist[m] != INT_MAX && dist[m] + cost < dist[n]) {
            printf("Exista un ciclu negativ.");
            return;
        }
    }

    printBellmanSol(dist, gr->V, path);

    free(dist);
    free(path);
}

由于没有引用边缘索引,只要它是唯一且连续的,您应该考虑自动递增。 除了边缘索引E ,还有一个新的边缘容量。 这是传递给createGraph的数字,最初设置计数器E = 0 你可以用少一个参数来编写你的addOrientedEdge 取下一个边缘索引。

static void addOrientedEdge(struct Graph* graph, int source, int destination, int cost) {
    const int index = graph->E;
    assert(graph && graph->E < graph->E_capacity);
    graph->edge[index].src = source;
    graph->edge[index].dest = destination;
    graph->edge[index].cost = cost;
    graph->E++;
    graph->matrix[source][destination] = cost;
}

这将使您不必担心边缘数字。

缺少导致问题的边缘。 感谢@user3386109 看到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM