How to compute directed graph diameter in C++ -
this question has answer here:
- algorithm diameter of graph? 9 answers
i have directed graph given matrix , need write program (c++) computes it's diameter. i'm lost when comes this. there known algorithm this? \
how think should go:
- convert undirected graph (for directedmatrix[i][j] !=0 , 1 nrnodes , j i+1 nrnodes, make matrix[j][i]=matrix[i][j]=directedmatrix[i][j])
- compute max distance 2 nodes ( distacematrix[i][j] = max distance node node j; distancematrix[i][i] = min)
- find maxim value above matrix , that's our answer.
thoughts , optimizations?
assuming number of nodes not great, simple solution use floyd-warshall algorithm find shortest paths between pairs of nodes , take greatest one. following code demonstrates it:
#include <cstdio> using namespace std; #define max 107 #define not_connected -1 int distance[max][max]; //number of nodes int nodescount; //initialize distances void initialize(){ (int i=0;i<max;++i){ (int j=0;j<max;++j){ distance[i][j]=not_connected; } distance[i][i]=0; } } int main(){ initialize(); //get nodes count scanf("%d", &nodescount); //edges count int m; scanf("%d", &m); while(m--){ //nodes - let indexation begin 1 int a, b; //edge weight int c; scanf("%d %d %d", &a, &b, &c); distance[a][b]=c; } //floyd-warshall (int k=1;k<=nodescount;++k){ (int i=1;i<=nodescount;++i){ if (distance[i][k]!=not_connected){ (int j=1;j<=nodescount;++j){ if (distance[k][j]!=not_connected && (distance[i][j]==not_connected || distance[i][k]+distance[k][j]<distance[i][j])){ distance[i][j]=distance[i][k]+distance[k][j]; } } } } } int diameter=-1; //look distant pair (int i=1;i<=nodescount;++i){ (int j=1;j<=nodescount;++j){ if (diameter<distance[i][j]){ diameter=distance[i][j]; printf("%d %d\n", i, j); } } } printf("%d\n", diameter); return 0; }
Comments
Post a Comment