Dijkstra算法详解(二)

2014-11-24 09:11:27 · 作者: · 浏览: 1
itGraph(&mGraph,n);
for(i=0;i {
scanf("%d %d %d",&A,&B,&templen);
mGraph.matrix[A][B]=templen;
}


in[1]=1;
path[1]=1; //sava path
Len[1]=0;

for(i=2;i<=n;i++)
{
Len[i]=mGraph.matrix[1][i]; //Init the len
if(Len[i]!=INFINITE)path[i]=1;
}

min=0;
si=1;

while(count {
tempmin=INFINITE;
for(i=1;i<=n;i++)
{
if(in[i]==0&&Len[i] {
tempmin=Len[i];
si=i;
}
}
in[si]=1;

for(i=1;i<=n;i++) //updata the length
{
if(in[i]==0&&(tempmin+mGraph.matrix[si][i])
{
Len[i]=tempmin+mGraph.matrix[si][i];
path[i]=si;
}
}
count++;
}

mstack s;
for(i=1;i<=n;i++)
{
temp=i;
InitStack(&s);
if(path[temp]==0)
{
printf("no path\n");
continue;
}
while(path[temp]!=1)
{
push(&s,path[temp]);
temp=path[temp];
}
printf("1-->");
while(s.bottom!=s.top)
{
printf("%d-->",pop(&s));
}
printf("%d min length is %d\n",i,Len[i]);

}

}
return 0;
}

附上上面那张图的结果(V0节点为1,V1节点为2.。。。以此类推)