今日主要学习了图中寻找最短路径的算法:迪杰斯特拉算法和弗洛伊德算法
迪杰斯特拉算法:

include <stdio.h>

include <stdlib.h>

include <limits.h>

include <stdbool.h>

// 找到未确定最短路径的顶点中距离源点最近的顶点
int minDistance(int dist[], bool sptSet[], int numVertices) {
int min = INT_MAX, min_index;
for (int v = 0; v < numVertices; v++) {
if (sptSet[v] == false && dist[v] < min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}

// Dijkstra 算法实现
void dijkstra(Graph* graph, int src) {
int dist[graph->numVertices];
bool sptSet[graph->numVertices];

for (int i = 0; i < graph->numVertices; i++) {
    dist[i] = INT_MAX;
    sptSet[i] = false;
}

dist[src] = 0;

for (int count = 0; count < graph->numVertices - 1; count++) {
    int u = minDistance(dist, sptSet, graph->numVertices);
    sptSet[u] = true;

    AdjListNode* temp = graph->adjLists[u];
    while (temp!= NULL) {
        int v = temp->dest;
        int weight = 1;  // 假设边的权重默认为 1,如有需要可修改
        if (sptSet[v] == false && dist[u] + weight < dist[v]) {
            dist[v] = dist[u] + weight;
        }
        temp = temp->next;
    }
}

// 输出源点到各个顶点的最短路径距离
for (int i = 0; i < graph->numVertices; i++) {
    printf("从源点 %d 到顶点 %d 的最短路径距离为: %d\n", src, i, dist[i]);
}

}

弗洛伊德算法:

include <stdio.h>

include <stdlib.h>

// Floyd 算法实现
void floyd(Graph* graph) {
int dist[graph->numVertices][graph->numVertices];
for (int i = 0; i < graph->numVertices; i++) {
for (int j = 0; j < graph->numVertices; j++) {
if (i == j) {
dist[i][j] = 0;
} else {
dist[i][j] = INT_MAX;
}
AdjListNode* temp = graph->adjLists[i];
while (temp!= NULL) {
if (temp->dest == j) {
dist[i][j] = 1; // 假设边的权重默认为 1,如有需要可修改
break;
}
temp = temp->next;
}
}
}

for (int k = 0; k < graph->numVertices; k++) {
    for (int i = 0; i < graph->numVertices; i++) {
        for (int j = 0; j < graph->numVertices; i++) {
            if (dist[i][k] + dist[k][j] < dist[i][j]) {
                dist[i][j] = dist[i][k] + dist[k][j];
            }
        }
    }
}

// 输出任意两点间的最短路径距离
for (int i = 0; i < graph->numVertices; i++) {
    for (int j = 0; j < graph->numVertices; j++) {
        if (dist[i][j] == INT_MAX) {
            printf("从顶点 %d 到顶点 %d 无路径\n", i, j);
        } else {
            printf("从顶点 %d 到顶点 %d 的最短路径距离为: %d\n", i, j, dist[i][j]);
        }
    }
}

}

posted on 2025-01-10 19:07  Swishy  阅读(17)  评论(0)    收藏  举报