[Discrete Mathematics] Practice 2 Floyd–Warshall Algorithm

Target

Given a distance matrix, use the Floyd–Warshall algorithm programming (C language) to find the shortest distance between any two points.


principle

The Floyd algorithm is commonly used to find the multi-source shortest path. By comparing the direct distance and the sum of the transit distances from each point, if the transit distance is shorter than the direct distance, it is the current shortest path. For example: the distance from place A to place B is 5, the distance from A to C is 2, and the distance from C to B is 2. In this case, you can go from C to B, and the shortest distance is 2 + 2 = 4. Floyd's core algorithm is as follows:

for (int i = 0; i < 4; i++)  
{
    
      
    for (int j = 0; j < 4; j++)  
    {
    
      
        for (int k = 0; k < 4; k++)  
        {
    
      
            if (matrix[i][j] > matrix[i][k] + matrix[k][j])  
            {
    
      
                matrix[i][j] = matrix[i][k] + matrix[k][j];  
            }  
        }  
    }  
}

Design and implementation (code snapshots and code)

insert image description here

#include <stdio.h>
// 输入一个4 * 4的矩阵
void input_matrix(int matrix[4][4])
{
    
    
    printf("若无法到达该点请输入10000\n");
    for (int i = 0; i < 4; i++)
    {
    
    
        printf("请输入第%d行数据\n", i + 1);
        scanf("%d %d %d %d", &matrix[i][0], &matrix[i][1], &matrix[i][2], &matrix[i][3]);
    }
}
// 输出Floyd最短路径矩阵
void output_matrix(int matrix[4][4])
{
    
    
    for (int i = 0; i < 4; i++)
    {
    
    
        for (int j = 0; j < 4; j++)
        {
    
    
            if (matrix[i][j] >= 10000)
                printf("*\t");
            else
                printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

int main()
{
    
    
    int matrix[4][4];
    input_matrix(matrix);
    for (int k = 0; k < 4; k++)
    {
    
    
        for (int i = 0; i < 4; i++)
        {
    
    
            for (int j = 0; j < 4; j++)
            {
    
    
                if (matrix[i][j] > matrix[i][k] + matrix[k][j])
                    matrix[i][j] = matrix[i][k] + matrix[k][j];
            }
        }
    }
    output_matrix(matrix);
    return 0;
}

Screenshots of the running interface and results

range0
2 6 4 ∞ 0 3 ∞ 7 ∞ 0 1 5 ∞ 12 0 \begin{matrix} &0 &2 &6 &4 \\ &\infty &0 &3 &\infty \\ &7 &\infty &0 &1 \\ &5 &\ . infty &12&0\\\end{matrix}0752063012410

Matrix calculated by Floyd algorithm
0 2 5 4 9 0 3 4 6 8 0 1 5 7 10 0 \begin{matrix} &0 &2 &5 &4 \\ &9 ​​&0 &3 &4 \\ &6 &8 &0 &1 \\ &5 &7 &10 &0 \\ \end{matrix}09652087530104410
insert image description here


epilogue

If you have any questions, please leave a message to discuss. If you think this article is helpful to you, can you give me a free like? The communication between us is my biggest motivation!


References: Floyd's shortest path algorithm with only five elements

Guess you like

Origin blog.csdn.net/Zchengjisihan/article/details/131613295