Floyd algorithm, one of the shortest path algorithms

Source: Internet
Author: User

Floyd algorithm

The Floyd algorithm can be used to solve the shortest path problem between any two vertices.

Core formula:

      Edge [I] [J] = min {edge [I] [J], edge [I] [k] + edge [k] [J]}.

That is to say, we can relax by inserting the vertex between I and j and comparing the path size.

First, we define a two-dimensional array edge [maxn] [maxn] to store Graph Information.

 

After the edge array of the graph is initialized

 

It is equivalent to the distance between any two points that cannot pass through other points.

Code1:

1 // After vertex 2 for (I = 1; I <= N; I ++) 3 for (j = 1; j <= N; j ++) 4 If (E [I] [J]> E [I] [1] + E [1] [J]) E [I] [J] = E [I] [1] + E [1] [J];

In this example, vertex 1 is allowed as the center point to relax the distance and save the result after relaxation.

Code2:

1 // After vertex 2 for (I = 1; I <= N; I ++) 3 for (j = 1; j <= N; j ++) 4 If (E [I] [J]> E [I] [2] + E [2] [J]) E [I] [J] = E [I] [2] + E [2] [J];

Allow vertex 1 and vertex 2 to relax and save as intermediate points. (Not always relaxed !)

.....

Core code of Floyd:

 

1 for(k=1;k<=n;k++)2     for(i=1;i<=n;i++)3         for(j=1;j<=n;j++)4             if(e[i][j]>e[i][k]+e[k][j])5                  e[i][j]=e[i][k]+e[k][j];

 

The basic idea of this Code is: In the beginning, it is allowed to transit only through vertex 1, and then only through vertex 1 and vertex 2 ...... 1 ~ All vertices on N are transitioned to find the shortest path between any two points. In a word, the shortest distance from vertex I to vertex J is only the first K.

Time Complexity: O (N ^ 3)

Some of the image text is taken from the blog of Aha lei.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.