求最短路径程序,要求如下:

求最短路径程序,要求如下:,第1张

我想你应该使用matlab来编程吧,c是不好解决这类问题的。首先你应该有10个分店的坐标值,各店之间能否互相达到的零一领结矩阵这两组数据,否则是无法求的。matlab的导入数据可以直接importdate *** 作,用两个变量分别保存导进的数据。利用10*2的坐标矩阵可以求出一个10*10的任意两点之间的直接距离,作为各点的权值,这个程序就不用我写了吧,然后直接把两个矩阵相乘,便得到了可以直接连通的距离领结矩阵,不连通的用无穷大表示,对角线为0。

其实解决这一问题的方法是由 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}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/7827620.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-10
下一篇 2023-04-10

发表评论

登录后才能评论

评论列表(0条)

保存