`
Dustman
  • 浏览: 13676 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Floyd-Warshall

阅读更多
就是求所有顶点对的最短路径长度


#include <iostream>
#include <vector>

using namespace std;

typedef struct{
  int vexs[10];
  int edges[10][10];
  int n;
  int e;
}MGraph;

#define INFINITE 2048

void CreateGraphM(MGraph *G){

  int N1,N2;

  cout<<"Enter the number of vertexs and edges: "<<endl;
  cin>>(G->n)>>(G->e);

  for(int i=0;i<G->n;i++)
    cin>>(G->vexs[i]);

  for(int i=0;i<G->n;i++)
    for(int j=0;j<G->n;j++)
      G->edges[i][j]=-1;
  
  cout<<"EDGES: "<<endl;

  for(int k=0;k<G->e;k++){
    int weight;
    cin>>N1>>N2>>weight;
    G->edges[N1-1][N2-1]=weight;
  }

  return;
}

vector< vector<int> > Floyed_Warshall(MGraph *G){
  
  vector< vector<int> > Dist(G->n,vector<int>(G->n));
  
  for(int i=0;i<G->n;i++)
    for(int j=0;j<G->n;j++)
      Dist[i][j] = G->edges[i][j];

  for(int i=0;i<G->n;i++)
    Dist[i][i] = 0;

  for(int i=0;i<G->n;i++)
    for(int j=0;i<G->n;i++)
      for(int k=0;i<G->n;i++)
        if(Dist[j][i] + Dist[i][k] < Dist[j][k] && \
           Dist[j][i] != -1 &&                     \
           Dist[i][k] != -1)
          Dist[j][k] = Dist[j][i] + Dist[i][k];

  return Dist;
}

int main()
{
  vector< vector<int> > Dist;
  MGraph *G = new MGraph;

  CreateGraphM(G);

  Dist = Floyed_Warshall(G);

  cout<<endl;

  for(int i=0;i<G->n;i++)
    for(int j=0;j<G->n;j++)
      if(Dist[i][j]!=-1 && i!=j)
        cout<<i+1<<" "<<j+1<<" "<<Dist[i][j]<<endl;
  
  cout<<endl;

  delete G;

  return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics