图论之Floyd算法
程序员文章站
2022-04-30 09:08:58
...
图论之Floyd算法
找图中任意两点之间的最小距离
/*存储模式:邻接矩阵
遍历模式:Floyd算法*/
#include<iostream>
#define MAXNODE 50
const int MAX_INT = 2147483647;
using namespace std;
class Graph{
public:
Graph(){
cout << "Hi~Nice to meet you " << endl;
Init();
}
void Init(){
int i,j;
cout << "请输入结点总数:";
cin >> this->num_node;
for( i=0;i<MAXNODE;i++ ){
for( j=0;j<MAXNODE;j++ ){
map[i][j]=-1;//如果说两点之间没有连接,就把之间的距离赋为-1
D[i][j]=-1;
}
}
for( i=0;i<MAXNODE;i++ ){
node[i]=i;
map[i][i]=0;
D[i][i]=0;
}
int n1=0,n2=0,len;
cout << "在一行中输入两个结点之间的连接关系:(以-1 -1结尾)" << endl;
while( (n1 != -1) && (n2 != -1) ){
cout << "点、点、权值:";
cin >> n1 >> n2>>len;
map[n1][n2]=len;
map[n2][n1]=len;
D[n1][n2]=D[n2][n1]=len;
}
cout << endl <<"--------------高能预警,我要Floyd了!!!!!!----------" << endl;
cout << "巴拉巴拉......." <<endl << endl;
ShortestPath_Floyd();
PrintShortestPath();
}
void Debug(){
int i,j;
cout << "----------D-----------:" << endl;
for( i=0;i<num_node;i++ ){
for( j=0;j<num_node;j++ ){
cout << D[i][j] << " ";
}
cout << endl;
}
}
bool Judge(int i,int j,int k){
if( (D[i][k] != -1) && (D[k][j] != -1) && ( (D[i][j] > D[i][k]+D[k][j]) || ( D[i][j] == -1 ) )) return true;
else return false;
}
void ShortestPath_Floyd();
void PrintShortestPath();
private:
int node[MAXNODE];
int num_node;
int map[MAXNODE][MAXNODE];
int D[MAXNODE][MAXNODE];//用于存放任意两点之间的距离
};
void Graph::ShortestPath_Floyd(){
int i,j,k;
int temp1,temp2;
for( k=0;k<num_node;k++ ){
cout << endl <<"序号" <<k << endl;
Debug();
for( i=0;i<num_node;i++ ){
for( j=i+1;j<num_node;j++ ){
if( Judge(i,j,k) ){
D[j][i] = D[i][j] = D[i][k] + D[k][j];
//Debug();
}
}
}
}
}
void Graph::PrintShortestPath(){
int i,j,k;
for( i=0;i<num_node;i++ ){
for( j=i+1;j<num_node;j++ ){
if( D[i][j] == -1 )
{
printf("\n%d和%d之间已经有了一道可悲的鸿沟!!!\n\n",i,j);
continue;
}
printf("%d到%d的最短距离是:%d\n",i,j,D[i][j]);
}
}
}
int main()
{
Graph graph;
return 0;
}
/*
0 4 100
0 3 30
0 1 10
1 2 50
2 3 20
2 4 10
3 4 60
-1 -1 0
*/
下一篇: 在AS3中删除一个XML节点