Floyd algorithm Template

Source: Internet
Author: User

Floyd can find the shortest distance between any two points, and the code is relatively simple. It is still very efficient for sparse graphs, but the time complexity is high due to the three for loops, not suitable for dense graphs.

Floyd algorithm template (Lite version ):

Void Floyd () {int Dist [maxn] [maxn]; // The shortest distance from Dist storage I to J for (int K = 1; k <= N; k ++) for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) if (Dist [I] [k] + dist [k] [J] <Dist [I] [J]) dist [I] [J] = DIST [I] [k] + dist [k] [J]; // continuously update the Shortest Path}

Record Shortest Path template:

Void Floyd () {for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) {Dist [I] [J] = map [I] [J], path [I] [J] = 0 ;}for (int K = 1; k <= N; k ++) for (INT I = 1; I <= N; I ++) for (Int J = 1; j <= N; j ++) if (Dist [I] [k] + dist [k] [J] <Dist [I] [J]) {Dist [I] [J] = DIST [I] [k] + dist [k] [J]; path [I] [J] = K; // path records the maximum vertex in the path} void output (int I, Int J) // recursively outputs the path. I is the starting point, J is the end {if (I = J) return; If (path [I] [J] = 0) cout <j <''; else {output (I, path [I] [J]); output (path [I] [J], j );}}


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.