其实解决这一问题的方法是由 Floyd R W 提出的算法,称之为 Floyd 算法。 给你一个求6个点任意两点间的最短距离的例子,这里的数据是自己输的,你有数据文件的话可以直接导。clearclc
n=6a=zeros(n)
a(1,2)=50a(1,4)=40a(1,5)=25a(1,6)=10
a(2,3)=15a(2,4)=20a(2,6)=25a(3,4)=10a(3,5)=20
a(4,5)=10a(4,6)=25a(5,6)=55
a=a+a'M=max(max(a))*n^2%M为充分大的正实数
a=a+((a==0)-eye(n))*M
path=zeros(n)
for k=1:n
for i=1:n
for j=1:n
if a(i,j)>a(i,k)+a(k,j)
a(i,j)=a(i,k)+a(k,j)
path(i,j)=k
end
end
end
end
a, path 得到的a便是任意两点间的最短距离。
#include#include#defineMAXV100#defineINF32767intvisited[MAXV]typedefintInfoTypetypedefstruct{intnoInfoTypeinfo}VertexTypetypedefstruct{intedges[MAXV][MAXV]intn,eVertexTypevexs[MAXV]}MGraphtypedefstructANode{intadjvexstructANode*nextarcInfoTypeinfo}ArcNodetypedefintVertextypedefstructVnode{VertexdataArcNode*firstarc}VNodetypedefVNodeAdjList[MAXV]typedefstruct{AdjListadjlistintn,e}ALGraphvoidMatToList(MGraphg,ALGraph*&G){inti,jArcNode*pG=(ALGraph*)malloc(sizeof(ALGraph))for(i=0iadjlist[i].firstarc=NULLfor(i=0i=0j--)if(g.edges[i][j]!=0){p=(ArcNode*)malloc(sizeof(ArcNode))p->adjvex=jp->nextarc=G->adjlist[i].firstarcG->adjlist[i].firstarc=p}G->n=g.nG->e=g.e}voidDispAdj(ALGraph*G){intiArcNode*pfor(i=0ini++){p=G->adjlist[i].firstarcprintf("%3d:",i)while(p!=NULL){printf("%3d",p->adjvex)p=p->nextarc}printf("\n")}}voidDFSALL(ALGraph*G,intv,intpath[],intd){ArcNode*pvisited[v]=1path[d]=vd++if(d==G->n){for(intk=0kadjlist[v].firstarcwhile(p!=NULL){if(visited[p->adjvex]==0)DFSALL(G,p->adjvex,path,d)p=p->nextarc}visited[v]=0}intmain(){intpath[MAXV],i,j,v=1MGraphgALGraph*Gg.n=5g.e=8intA[MAXV][MAXV]={{0,1,0,1,1},{1,0,1,1,0},{0,1,0,1,1},{1,1,1,0,1},{1,0,1,1,0}}for(i=0i<g.ni++)for(j=0j<g.nj++)g.edges[i][j]=A[i][j]MatToList(g,G)for(i=0i<g.ni++)visited[i]=0printf("图G的邻接表:\n")DispAdj(G)printf("从顶点%d出发的所有深度优先序列:\n",v)DFSALL(G,v,path,0)printf("\n")return0}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)