前阵子做数据结构的最短路径,到现在都没做出来~~
下面是我的源程序,使用迪杰斯特拉算法,编译没错,可是运行不了。好像是分配空间的问题~~大家看看有什么问题?
在此先谢谢大家!!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define Max 65535
#define Maxvexnum 11
#define T 1
#define F 0
typedef int pathM[Maxvexnum][Maxvexnum];
typedef int spathTable[Maxvexnum];
typedef struct{
int weight;
}Adjmatrix[Maxvexnum][Maxvexnum];
typedef struct{
char *vexs[Maxvexnum]; //存储顶点的向量
Adjmatrix arcs;
int vexnum,arcnum;
}graph;
void spath(graph *G,int v0,pathM p,spathTable D){
//用Dijkstra算法求有向图G的v0顶点到其余顶点的最短路径p[v]及其带权长度D[v]
//若p[v][w]为true,则w是从v0到当前求得最短路径上的顶点
//final[v]为true当且仅当v属于s,即已经求得从v0到v的最短路径
int min,i,v,w;
int final[Maxvexnum];
for(v = 0; v < G->vexnum; ++v){
final[v] = F;
D[v] = G->arcs[v0][v].weight;
for(w = 0; w < G->vexnum; ++w)
p[v][w] = F;
if(D[v] < Max) {p[v][v0] = T; p[v][v] = T;}
}
D[v0] = 0; final[v0] = T;
for(i = 1; i < G->vexnum; ++i){
min = Max;
for(w = 0; w < G->vexnum; ++w)
if(!final[w] && D[w] < min)
{v = w; min = D[w];}
final[v] = T;
for(w = 0; w < G->vexnum; ++w)
if(!final[w] && (min + G->arcs[v][w].weight < D[w])){
D[w] = min + G->arcs[v][w].weight;
for(i = 0; i < G->vexnum; ++i)
p[w] = p[v];
p[w][w] = T;
}//if
}//for
}
int locatevex(graph *G,char *v){
int i;
for(i = 0; i < G->vexnum; ++i)
if(strcmp(v , G->vexs) == 0)
return i;
return -1;
}
void createDN(graph *G){
int i,j,k,w,count;
char *V1,*V2;
char temp[10];
printf(“请输入有向网G的顶点数,弧数!\n”);
scanf(“%d,%d”,&G->vexnum,&G->arcnum);
printf(“请输入%d个顶点的值:\n”,G->vexnum);
for(i = 0; i < G->vexnum; ++i){
scanf(“%s”,temp);
count = 0;
while(temp[count++] != ‘\0′)
G->vexs = (char *)malloc(count * sizeof(char)); //不知道这里是否正确分配空间??
}
for(i = 0; i < G->vexnum; ++i)
for(j = 0; j < G->vexnum; ++j)
G->arcs[j].weight = Max;
printf(“请输入%d条弧的弧尾 弧头(以空格作为间隔):\n”,G->arcnum);
for(k = 0; k < G->arcnum; ++k){
scanf(“%s%s%d”,&V1,&V2,&w); //输入是在这里出现问题的!!!
i = locatevex(G,V1);
j = locatevex(G,V2);
G->arcs[j].weight = w;
}
}
void display(graph *G){
int i,j;
printf(“%d个顶点%d条边或弧的有向网。顶点依次是: “,G->vexnum,G->arcnum);
for(i = 0; i< G->vexnum; ++i) // 输出G.vexs
printf(“%s “,G->vexs);
printf(“\nG.arcs.weight\n”); //输出G.arcs.weight
for(i = 0; i < G->vexnum; ++i){
for(j = 0; j < G->vexnum; ++j)
printf(“%10d”,G->arcs[j].weight);
printf(“\n”);
}
}
void main()
{
int i,j;
graph G;
pathM p;
spathTable D;
createDN(&G);
display(&G);
spath(&G,0,p,D);
printf(“the pathM p[j] are:\n”);
for(i = 0; i < G.vexnum; ++i){
for(j = 0; j < G.vexnum; ++j)
printf(“%4d”,p[j]);
printf(“\n”);
}
printf(“the shortest path weight of %s to every vex are:\n”,G.vexs[0]);
for(i = 0; i < G.vexnum; ++i)
if(i)
printf(“%s—-%s: %4d\n”,G.vexs[0],G.vexs,D);
}
多谢大家参看!!
>> 本文固定链接: http://www.vcgood.com/archives/2031
没人救我吗?
问题已经解决,谢谢关注!
问题出在顶点分配空间处~~