软件测试相关:
#include<iostream>
using namespace std;
#define INFTY 65535 //边不相邻用INFTY代替
//存储图的邻接矩阵
int m[4][4]={{0,1,INFTY,4},{INFTY,0,9,2},{3,5,0,8},{INFTY,INFTY,6,0}};
class MGraph
{
public:
MGraph(int size);
~MGraph();
void Floyd();
void shortestway(int u,int v);
private:
int **a,**d,**path;
int n;
};
MGraph::MGraph(int size)
{
n=size;
a=new int*[n];
for(int i=0;i<n;++i)
a[i]=new int[n];
for( i=0;i<n;++i)
for(int j=0;j<n;++j)
a[i][j]=m[i][j];//用邻接矩阵初始化
}
MGraph::~MGraph()
{
for(int i=0;i<n;++i)
delete []a[i];
delete []a;
a=NULL;
for( i=0;i<n;++i)
delete []d[i];
delete []d;
d=NULL;
for( i=0;i<n;++i)
delete []path[i];
delete []path;
path=NULL;
}
void MGraph::Floyd()
{
int i,j,k;
d=new int*[n];
path=new int*[n];
for( i=0;i<n;++i)
{
d[i]=new int[n];
path[i]=new int[n];
for(j=0;j<n;++j)
{
d[i][j]=a[i][j];
if(i!=j && m[i][j]<INFTY) path[i][j]=i;//i表示弧的起点
else path[i][j]=-1;//其实感觉这个-1没啥用,只是不让它和i点的值冲突即可
}
}
for(k=0;k<n;++k)
for(i=0;i<n;++i)
for(j=0;j<n;++j)
if(d[i][k]+d[k][j]<d[i][j])
{
d[i][j]=d[i][k]+d[k][j];
path[i][j]=path[k][j];//k这是一个新加入的点,将k加入path中去
}
}
void MGraph::shortestway(int u,int v)//输出最短路径
{
int way[4];
int q=0;
int w=v;
while (w!=u)
{
way[q++] = path[u][w];
w=path[u][w];
}
cout<<u<<" 到 "<<v<<" 的最短路径为:";
--q;
for (int j=q; j>=0; j--)
cout<<way[j]<<" ->";
cout<<v<<endl;
}
void shortestPath(MGraph g, int node1, int node2){
g.Floyd();
g.shortestway(node1,node2);
}
int main()
{
MGraph *g=new MGraph(4);
//g.Floyd();
//g.shortestway(0,2);
shortestPath(*g,0,2);
system("pause");
return 0;
}