Shortest Path-Floyd algorithm

Source: Internet
Author: User

In the previous blog, I talked about the Dijkstra algorithm. In this blog, I want to explain the Floyd algorithm. The Dijkstra algorithm is a greedy algorithm, and the Floyd algorithm is an algorithm for dynamic planning:

The specific algorithm is as follows:

One matrix is used to store the shortest path, and the other matrix is used to store the front vertex;

#include <iostream>using namespace std;#define Max 5#define Infinity 65535void main(){int V[Max][Max]={0,8,32,Infinity,Infinity,12,0,16,15,Infinity,Infinity,29,0,Infinity,13,Infinity,21,Infinity,0,7,Infinity,Infinity,27,19,0};int G[Max][Max];for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){G[i][j]=-1;}}for(int k=0;k<Max;k++){for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){if(V[i][k]+V[k][i]<V[i][j]){V[i][j]=V[i][k]+V[k][j];G[i][j]=k;}}}}for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){cout<<V[i][j]<<" ";}cout<<endl;}for(int i=0;i<Max;i++){for(int j=0;j<Max;j++){cout<<G[i][j]<<" ";}cout<<endl;}}


Shortest Path-Floyd algorithm

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.