typedef struct{ int v; int parent; }QUEUE1; 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){ while(!QueueEmpty(qu)){ deQueue(qu,&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; } }加入getQueueElem函数
时间: 2023-10-20 21:05:21 浏览: 84
在上述代码中,需要加入 `getQueueElem` 函数,用于根据队列中元素的 `parent` 属性找到其对应的元素。可以按照以下方式实现该函数:
```c++
QUEUE1 getQueueElem(SqQueue *qu, int parent) {
QUEUE1 elem;
int i = qu->front;
while (i != qu->rear) {
i = (i + 1) % MAXSIZE;
if (qu->data[i].v == parent) {
elem = qu->data[i];
break;
}
}
return elem;
}
```
在使用该函数时,需要将 `qu` 传入 `getQueueElem` 函数中,如下所示:
```c++
elem = getQueueElem(qu, elem.parent);
```
综上所述,修改后的代码如下所示:
```c++
typedef struct {
int v;
int parent;
} QUEUE1;
int BFSA(AdjGraph *G, int u, int v) {
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;
}
ArcNode *p;
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) % MAXSIZE;
if (qu->data[i].v == parent) {
elem = qu->data[i];
break;
}
}
return elem;
}
```
阅读全文