The Floyd-Warshall algorithm transmits the closure and the floyd-warshall algorithm at any two points.

Source: Internet
Author: User

The Floyd-Warshall algorithm transmits the closure and the floyd-warshall algorithm at any two points.

The Floyd-Warshall algorithm is a powerful tool for solving the shortest of any two points. It is also applicable to the presence of negative edges.

DP concept. Assume that the shortest distance from I to j is d [K] [I] [j].
Then, the first K + 1 points can be divided into two situations.
① K + 1 point is used for the shortest circuit from I to j (d [k + 1] [I] [j] = d [k] [I] [j])
② The shortest path from I to j does not use the K + 1 point (d [k + 1] [I] [j] = d [k] [I] [k] + d [k] [k] [j]);
So,D [k + 1] [I] [j] = min (d [k] [I] [j], d [k] [I] [k] + d [k] [k] [j])

You can use a scrolling array to write a two-dimensional array.
D [I] [j] = min (d [I] [j], d [I] [k] + d [k] [j])

The Floyd algorithm can be solved in O (V ^ 3) Time to determine whether a negative circle exists in the graph, you only need to check whether d [I] [I] is a negative vertex I.

Code
// D [I] [j] indicates the weight of I-> j. If no value exists, it is set to INF, but d [I] [I] is set to 0for (int k = 0; k <V; k ++) {for (int I = 0; I <V; I ++) {for (int j = 0; j <V; j ++) {d [I] [j] = min (d [I] [j], d [I] [k] + d [k] [j]) ;}}

Because the implementation is very simple, if the complexity is within the tolerable range, the Floyd-Warshall algorithm can also be used for solving the single-source shortest.

In a directed graph, you can use the Floyd algorithm to determine whether a path exists for each two points.Passing Closure.
You only need to change itD [I] [j] = d [I] [j] | (d [I] [k] & d [k] [j])(Preprocessing also needs to change)

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.