typedef struct{ int v; int parent; }QUEUE1; QUEUE1 getQueueElem(SqQueue *qu,int parent); int BFSA(AdjGraph *G,int u,int v) { ArcNode *p; SqQueue *qu; InitQueue(qu); int visited[MAXV]; for(int i=0;i<G->n;i++){ visited[i]=0; } QUEUE1 elem; elem.v=u; elem.parent=-1; enQueue(qu,v); while(!QueueEmpty(qu)){ deQueue(qu,&v); if(elem.v==v){ break; } p=G->adjlist[elem.v].firstarc; while(p!=NULL){ int w=p->adjvex; if(visited[w]==0){ visited[w]=1; QUEUE1 new_v; new_v.v=w; new_v.parent=elem.v; enQueue(qu,w); } p=p->nextarc; } } if(elem.v!=v){ printf("不存在从%d到%d的路径\n",u,v); return -1; }else{ int len=0; while(elem.parent!=-1){ len++; elem=getQueueElem(qu,elem.parent); } printf("从%d到%d的最短路径长度为:%d\n",u,v,len); return len; } DestroyQueue(qu); } QUEUE1 getQueueElem(SqQueue *qu,int parent){ QUEUE1 elem; int i=qu->front; while(i!=qu->rear){ i=(i+1) % MAXV; if(qu->data[i].parent==parent){ elem=qu->data[i]; break; } } return elem; }修改上述程序
时间: 2023-12-01 18:04:55 浏览: 69
STM32 头文件stdint.h简略翻译
5星 · 资源好评率100%
上述程序需要修改一处错误,即在enQueue的时候应该将new_v入队,而不是将w入队。修改后的程序如下所示:
```
typedef struct{
int v;
int parent;
} QUEUE1;
QUEUE1 getQueueElem(SqQueue *qu, int parent);
int BFSA(AdjGraph *G, int u, int v) {
ArcNode *p;
SqQueue *qu;
InitQueue(qu);
int visited[MAXV];
for(int i = 0; i < G->n; i++) {
visited[i] = 0;
}
QUEUE1 elem;
elem.v = u;
elem.parent = -1;
enQueue(qu, elem);
while(!QueueEmpty(qu)) {
deQueue(qu, &elem);
if(elem.v == v) {
break;
}
p = G->adjlist[elem.v].firstarc;
while(p != NULL) {
int w = p->adjvex;
if(visited[w] == 0) {
visited[w] = 1;
QUEUE1 new_v;
new_v.v = w;
new_v.parent = elem.v;
enQueue(qu, new_v);
}
p = p->nextarc;
}
}
if(elem.v != v) {
printf("不存在从%d到%d的路径\n", u, v);
return -1;
} else {
int len = 0;
while(elem.parent != -1) {
len++;
elem = getQueueElem(qu, elem.parent);
}
printf("从%d到%d的最短路径长度为:%d\n", u, v, len);
return len;
}
DestroyQueue(qu);
}
QUEUE1 getQueueElem(SqQueue *qu, int parent) {
QUEUE1 elem;
int i = qu->front;
while(i != qu->rear) {
i = (i + 1) % MAXV;
if(qu->data[i].parent == parent) {
elem = qu->data[i];
break;
}
}
return elem;
}
```
阅读全文