1. 程式人生 > >最短路徑(Floyd演算法)

最短路徑(Floyd演算法)

 

Floyd演算法又稱為弗洛伊德演算法,插點法,是一種用於尋找給定的加權圖中頂點間最短路徑的演算法。

標頭檔案:Floyd.h

#ifndef FLOYD_H
#define FLOYD_H
#define INFINITY 65535
#define MAXVEX 20
#define MAXVEX 20
typedef int ShortPathTable[MAXVEX][MAXVEX];
typedef int ShortPosition[MAXVEX][MAXVEX];
typedef struct graph{
	int Vertex[MAXVEX]; //頂點資訊
	int Edge[MAXVEX][MAXVEX]; //邊表資訊
	int NumVertex,NumEdge; //圖的頂點數,邊數
}Graph;
void CreateGraph(Graph *G); //建立圖
void ShortestPath_Floyd(Graph *G,ShortPosition *p,ShortPathTable *d); //費洛伊德演算法
#endif //FLOYD_H


實現檔案:Floyd.cpp

#include "Floyd.h"
#include <stdio.h>
void CreateGraph(Graph *G)
{
	G->NumVertex = 9; //圖的頂點數為9
	G->NumEdge = 16;  //圖的邊為16

	for(int i = 0;i < G->NumVertex;++i) //初始化頂點資訊
		G->Vertex[i] = i;

	for(int i = 0;i < G->NumVertex;++i)		//初始化邊表資訊
		for(int j = 0;j < G->NumVertex;++j)
		{
			if(i == j)
				G->Edge[i][j] = 0;
			else
				G->Edge[i][j] = INFINITY;
		}
	//設定圖的邊表資訊
	G->Edge[0][1] = 1;
	G->Edge[0][2] = 5;

	G->Edge[1][2] = 3;
	G->Edge[1][3] = 7;
	G->Edge[1][4] = 5;

	G->Edge[2][4] = 1;
	G->Edge[2][5] = 7;

	G->Edge[3][4] = 2;
	G->Edge[3][6] = 3;

	G->Edge[4][5] = 3;
	G->Edge[4][6] = 6;
	G->Edge[4][7] = 9;

	G->Edge[5][7] = 5;
	G->Edge[6][7] = 2;
	G->Edge[6][8] = 7;
	G->Edge[7][8] = 4;

	for(int i = 0;i < G->NumVertex;++i)  //無向圖,存在反向連結
		for(int j = i;j < G->NumVertex;++j)
		{
			G->Edge[j][i] = G->Edge[i][j];
		}
}
void ShortestPath_Floyd(Graph *G,ShortPosition *p,ShortPathTable *d)
{
	for(int i = 0;i < G->NumVertex;++i) //初始化兩個矩陣
		for(int j = 0;j < G->NumVertex;++j)
		{
			(*p)[i][j] = j;					//p[i][j]為 j頂點的下標值
			(*d)[i][j] = G->Edge[i][j];		//d[i][j]的值為兩頂點間的權值
		}
	for(int k = 0;k < G->NumVertex;++k) //K為中轉頂點
	{
		for(int i = 0;i < G->NumVertex;++i)
		{
			for(int j = 0;j < G->NumVertex;++j)
			{
				if((*d)[i][j] > (*d)[i][k] + (*d)[k][j]) //如果兩頂點的距離大於經過中轉頂點的距離
				{
					(*d)[i][j] = (*d)[i][k] + (*d)[k][j];
					(*p)[i][j] = (*p)[i][k];
				}
			}
		}
	}
}


測試檔案:main.cpp

#include "Floyd.h"
#include <stdio.h>
int main()
{
	Graph G;
	int k;
	ShortPathTable d;
	ShortPosition p;
	CreateGraph(&G);
	ShortestPath_Floyd(&G,&p,&d);
	for(int i = 0;i < G.NumVertex;++i)
	{
		for(int j = i + 1;j < G.NumVertex;++j)
		{
			printf("V%d - V%d weight: %d",i,j,d[i][j]);
			k = p[i][j];
			printf(" path: V%d",i);
			while(k != j)
			{
				printf(" -> V%d",k);
				k = p[k][j];
			}
			printf(" -> V%d\n",j);
		}
	}
	printf("\n");
}