You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言打印Bellman-Ford算法的路径与最终距离矩阵?

Fixing Your Bellman-Ford Implementation in C

Hey there! I see you're stuck getting your Bellman-Ford algorithm up and running—especially with printing distances and paths. Let's break down the issues and build a working version step by step.

First, let's look at the truncated code snippet you provided (the incomplete bellMan function is a big part of the problem):

#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // You were missing this critical header for infinity values!

typedef struct edge {
    int s,d,w;
    struct edge *next;
} Edge;

typedef struct graph {
    int V,E;
    Edge *e;
} graph;

graph* createGraph(int v,int e) {
    graph* g=(graph*)malloc(sizeof(graph));
    g->V=v;
    g->E=e;
    g->e=(Edge*)malloc(sizeof(Edge)*e);
    return g;
}

// Your bellMan function was cut off—let's fix that!

Key Issues in Your Current Code

  • Missing header: <limits.h> is required to use INT_MAX (our stand-in for infinity in distance calculations).
  • Incomplete core logic: The Bellman-Ford function was truncated, so the relaxation, path tracking, and printing logic were missing entirely.
  • Uninitialized edge data: When you allocate the Edge array, you don’t populate the source (s), destination (d), and weight (w) values—this leads to garbage data and crashes.
  • No path/distance tracking setup: You haven’t declared arrays to store shortest distances and predecessor nodes (needed to reconstruct paths).

Working Bellman-Ford Implementation with Path & Distance Printing

Here's a complete, tested version that fixes all these issues:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef struct edge {
    int s, d, w;
} Edge; // We don't need the `next` pointer—Bellman-Ford uses an edge array, not adjacency lists

typedef struct graph {
    int V, E;
    Edge *edges;
} Graph;

Graph* createGraph(int v, int e) {
    Graph* g = (Graph*)malloc(sizeof(Graph));
    g->V = v;
    g->E = e;
    g->edges = (Edge*)malloc(sizeof(Edge) * e);
    return g;
}

// Bellman-Ford algorithm to find shortest paths from a source vertex
void bellmanFord(Graph* g, int source) {
    int V = g->V;
    int E = g->E;
    int dist[V];
    int parent[V]; // Tracks predecessor nodes to reconstruct paths

    // Step 1: Initialize distances to infinity and parents to -1
    for (int i = 0; i < V; i++) {
        dist[i] = INT_MAX;
        parent[i] = -1;
    }
    dist[source] = 0; // Distance to the source itself is 0

    // Step 2: Relax all edges V-1 times (max needed for shortest paths)
    for (int i = 1; i <= V-1; i++) {
        for (int j = 0; j < E; j++) {
            int u = g->edges[j].s;
            int v = g->edges[j].d;
            int weight = g->edges[j].w;
            // Only relax if u is reachable and we found a shorter path to v
            if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                parent[v] = u;
            }
        }
    }

    // Step 3: Check for negative-weight cycles (invalidates shortest paths)
    for (int j = 0; j < E; j++) {
        int u = g->edges[j].s;
        int v = g->edges[j].d;
        int weight = g->edges[j].w;
        if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {
            printf("Graph contains a negative-weight cycle! Shortest paths are undefined.\n");
            return;
        }
    }

    // Print distance matrix and reconstructed paths
    printf("Shortest Distances from Source %d:\n", source);
    for (int i = 0; i < V; i++) {
        printf("Vertex %d: Distance = ", i);
        if (dist[i] == INT_MAX) {
            printf("Unreachable | Path: N/A\n");
            continue;
        }
        printf("%d | Path: ", dist[i]);
        
        // Reconstruct path using parent array (reverse order first)
        int path[V], pathLen = 0;
        int temp = i;
        while (temp != -1) {
            path[pathLen++] = temp;
            temp = parent[temp];
        }
        // Print path from source to destination
        for (int k = pathLen-1; k >= 0; k--) {
            printf("%d", path[k]);
            if (k != 0) printf(" -> ");
        }
        printf("\n");
    }
}

int main() {
    // Example graph setup—adjust these values for your use case
    int V = 5; // Number of vertices
    int E = 8; // Number of edges
    Graph* g = createGraph(V, E);

    // Populate edges with (source, destination, weight)
    g->edges[0] = (Edge){0, 1, -1};
    g->edges[1] = (Edge){0, 2, 4};
    g->edges[2] = (Edge){1, 2, 3};
    g->edges[3] = (Edge){1, 3, 2};
    g->edges[4] = (Edge){1, 4, 2};
    g->edges[5] = (Edge){3, 2, 5};
    g->edges[6] = (Edge){3, 1, 1};
    g->edges[7] = (Edge){4, 3, -3};

    bellmanFord(g, 0); // Run algorithm starting from vertex 0

    // Clean up allocated memory to avoid leaks
    free(g->edges);
    free(g);
    return 0;
}

What This Fixes

  1. Added missing dependencies: <limits.h> provides the INT_MAX value we use for unreachable nodes.
  2. Simplified edge structure: Removed the unnecessary next pointer since Bellman-Ford works best with an edge array.
  3. Complete core logic: Implements all steps of Bellman-Ford: initialization, relaxation, negative cycle detection.
  4. Path reconstruction: Uses a parent array to build and print the shortest path for each vertex.
  5. Memory safety: Frees allocated memory to prevent leaks.

How to Adapt This to Your Graph

  • Change V and E to match your graph's vertex and edge count.
  • Replace the example edges in main() with your graph's source, destination, and weight values.
  • Call bellmanFord(g, your_source_vertex) to run the algorithm from your desired starting point.

This code should compile and run without issues, printing both the shortest distances and corresponding paths for each vertex.

内容的提问来源于stack exchange,提问作者Rahul Krishna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:16:46