typedef struct{ int v; int dist; }QUEUE1; int shortpathlen(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 e,e1; e.v=u; e.dist=0; enQueue(qu,e.dist); visited[u]=1; while(!QueueEmpty(qu)){ deQueue(qu,e.dist); u=e.v; if(u==v){ DestroyQueue(qu); return e.dist; } p=G->adjlist[u].firstarc; while(p!=NULL){ int w=p->adjvex; if(visited[w]==0){ e1.v=w; e1.dist=e.dist+1; enQueue(qu,e1.dist); visited[w]=1; } p=p->nextarc; } } DestroyQueue(qu); }修改上述代码,加入main函数
时间: 2023-06-20 17:08:36 浏览: 96
以下是修改后的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAXV 100
#define OK 1
#define ERROR 0
typedef struct ArcNode {
int adjvex; // 邻接点在顶点数组中的下标
struct ArcNode *nextarc; // 指向下一个邻接点的指针
} ArcNode;
typedef struct VNode {
int data; // 顶点的数据域,可以根据实际情况修改
ArcNode *firstarc; // 指向第一个邻接点的指针
} VNode, AdjList[MAXV];
typedef struct {
AdjList adjlist; // 邻接表
int n, e; // 顶点数和边数
} AdjGraph;
typedef struct {
int front, rear;
int data[MAXV];
} SqQueue;
int InitQueue(SqQueue *q) {
q->front = q->rear = 0;
return OK;
}
int QueueEmpty(SqQueue *q) {
return q->front == q->rear;
}
int enQueue(SqQueue *q, int e) {
if ((q->rear + 1) % MAXV == q->front)
return ERROR; // 队满
q->data[q->rear] = e;
q->rear = (q->rear + 1) % MAXV;
return OK;
}
int deQueue(SqQueue *q, int *e) {
if (q->front == q->rear)
return ERROR; // 队空
*e = q->data[q->front];
q->front = (q->front + 1) % MAXV;
return OK;
}
int CreateGraph(AdjGraph *G) {
printf("请输入顶点数和边数:");
scanf("%d %d", &G->n, &G->e);
printf("请依次输入顶点的值:");
for (int i = 0; i < G->n; ++i) {
scanf("%d", &G->adjlist[i].data);
G->adjlist[i].firstarc = NULL;
}
printf("请输入每条边的两个端点 u, v 及其权值:\n");
for (int k = 0; k < G->e; ++k) {
int i, j;
int w;
scanf("%d %d %d", &i, &j, &w);
ArcNode *p = (ArcNode *) malloc(sizeof(ArcNode));
p->adjvex = j;
p->nextarc = G->adjlist[i].firstarc;
G->adjlist[i].firstarc = p;
p = (ArcNode *) malloc(sizeof(ArcNode));
p->adjvex = i;
p->nextarc = G->adjlist[j].firstarc;
G->adjlist[j].firstarc = p;
}
return OK;
}
int shortpathlen(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;
}
int dist[MAXV];
for (int i = 0; i < G->n; i++) {
dist[i] = -1; // 初始化为-1,表示不可达
}
dist[u] = 0;
visited[u] = 1;
enQueue(qu, u);
while (!QueueEmpty(qu)) {
int u;
deQueue(qu, &u);
p = G->adjlist[u].firstarc;
while (p != NULL) {
int w = p->adjvex;
if (visited[w] == 0) {
dist[w] = dist[u] + 1;
visited[w] = 1;
enQueue(qu, w);
}
p = p->nextarc;
}
}
if (dist[v] == -1) {
printf("不存在从%d到%d的路径\n", u, v);
return -1;
} else {
printf("从%d到%d的最短路径长度为:%d\n", u, v, dist[v]);
return dist[v];
}
}
int main() {
AdjGraph G;
CreateGraph(&G);
int u, v;
printf("请输入起点和终点:");
scanf("%d %d", &u, &v);
shortpathlen(&G, u, v);
return 0;
}
```
阅读全文