编辑代码

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

#define SIZE 10

int graph[SIZE][SIZE] = {
    {0, 1, 0, 0, 0, 1, 0, 0, 0, 0},
    {1, 0, 1, 1, 0, 0, 1, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 1, 0, 0, 1, 0, 0},
    {0, 0, 0, 1, 0, 0, 0, 0, 1, 0},
    {1, 0, 0, 0, 0, 0, 1, 0, 0, 0},
    {0, 1, 0, 0, 0, 1, 0, 1, 0, 0},
    {0, 0, 0, 1, 0, 0, 1, 0, 1, 0},
    {0, 0, 0, 0, 1, 0, 0, 1, 0, 1},
    {0, 0, 0, 0, 0, 0, 0, 0, 1, 0}
};

void dijkstra(int graph[SIZE][SIZE], int source, int destination, int distance[SIZE])
{
    int visited[SIZE] = {0};
    int i, j;

    for (i = 0; i < SIZE; i++) {
        distance[i] = INT_MAX;
    }

    distance[source] = 0;

    for (i = 0; i < SIZE - 1; i++) {
        int min_distance = INT_MAX;
        int min_index;

        for (j = 0; j < SIZE; j++) {
            if (!visited[j] && distance[j] < min_distance) {
                min_distance = distance[j];
                min_index = j;
            }
        }

        visited[min_index] = 1;

        for (j = 0; j < SIZE; j++) {
            if (!visited[j] && graph[min_index][j] && distance[min_index] != INT_MAX &&
                distance[min_index] + graph[min_index][j] < distance[j]) {
                distance[j] = distance[min_index] + graph[min_index][j];
            }
        }
    }
}

int main()
{
    int distance[SIZE];
    int source, destination;
    //场所10个 名称为A1-A10
    
    source = 0; // A1
    destination = 9; // A10

    dijkstra(graph, source, destination, distance);

    printf("从A%d到A%d的最短路径为:%d\n", source + 1, destination + 1, distance[destination]);

    source = 2; // A3
    destination = 7; // A8

    dijkstra(graph, source, destination, distance);

    printf("从A%d到A%d的最短路径为:%d\n", source + 1, destination + 1, distance[destination]);

    return 0;
}