Data Structure-Implementation of Shortest Path in C language using the Floyd algorithm

Source: Internet
Author: User

The structure of data --- C language realizes the shortest path of Floyd (Floyd) algorithm
// This code integrates the code on the network.
// Floyd algorithm Floyd code
// Yang Xin
#include
#include
#define MAX_VERTEX_NUM 100 // Maximum number of vertices
#define MAX_INT 10000 // infinity

typedef int AdjType;
typedef struct
{
Int pi [MAX_VERTEX_NUM]; // A shortest path to store v to vi
Int end;
} PathType;
A
typedef char VType; // Set vertex to character type


// Graph represented by adjacency matrix
typedef struct
{
VType V [MAX_VERTEX_NUM]; // Vertex storage space
AdjType A [MAX_VERTEX_NUM] [MAX_VERTEX_NUM]; // Adjacency matrix
} MGraph;

int path [MAX_VERTEX_NUM] [MAX_VERTEX_NUM]; // The shortest path vector to each vertex
int D [MAX_VERTEX_NUM] [MAX_VERTEX_NUM]; // The shortest path length vector to each vertex


// Floyd algorithm
// Find the shortest path between any two points in the network G (represented by the adjacency matrix)
// D [] [] is the shortest path length matrix, path [] [] shortest path flag matrix
void Floyd (MGraph * G, int path [] [MAX_VERTEX_NUM], int D [] [MAX_VERTEX_NUM], int n)
{
Int i, j, k;
// Initialize
For (i = 0; iA [i] [j] A [i] [j];
}}
}

// Do n searches
For (k = 0; k D [i] [k] + D [k] [j])
{
D [i] [j] = D [i] [k] + D [k] [j]; // take the smaller one
Path [i] [j] = path [i] [k]; // Change the successor of Vi
}
}}}
}}
}
}


int main ()
{
Int i, j, k, v = 0, n = 6; // v is the starting point, n is the number of vertices
MGraph G;

// Initialize
AdjType a [MAX_VERTEX_NUM] [MAX_VERTEX_NUM] =
{
{0,12,18, MAX_INT, 17, MAX_INT},
{12,0,10,3, MAX_INT, 5},
{18,10,0, MAX_INT, 21,11},
{MAX_INT, 3, MAX_INT, 0, MAX_INT, 8},
{17, MAX_INT, 21, MAX_INT, 0,16},
{MAX_INT, 5,11,8,16,0}
};
For (i = 0; i
A

A

result:

Related Article

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.