赋权图的广度优先遍历C++
时间: 2023-05-22 16:03:16 浏览: 89
图的广度优先遍历
4星 · 用户满意度95%
很高兴为您解答问题!以下是C赋权图的广度优先遍历代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100
typedef int VertexType;
typedef int EdgeType;
typedef struct EdgeNode {
int adjvex; // 邻接点域,存储该顶点对应的下标
int weight; // 存储边的权值
struct EdgeNode *next; // 链域,指向下一个邻接点
}EdgeNode;
typedef struct VertexNode {
VertexType data; // 顶点信息
EdgeNode *firstedge; // 边表头指针
}VertexNode,AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList adjList;
int vexnum,edgenum; // 图中当前顶点数和边数
}Graph;
void CreateGraph(Graph *G) {
int i,j,k,w;
EdgeNode *e;
printf("请输入图中当前顶点数和边数(空格分隔):");
scanf("%d%d",&G->vexnum,&G->edgenum);
printf("请输入每个顶点的值:\n");
for(i = 0;i < G->vexnum;i++) {
scanf("%d",&G->adjList[i].data);
G->adjList[i].firstedge = NULL;
}
printf("请输入每条边的两个顶点以及对应的权值(空格分隔):\n");
for(k = 0;k < G->edgenum;k++) {
scanf("%d%d%d",&i,&j,&w); // 输入边的起点,终点,权值
e = (EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex = j;
e->weight = w;
e->next = G->adjList[i].firstedge; // 头插法
G->adjList[i].firstedge = e;
e = (EdgeNode*)malloc(sizeof(EdgeNode));
e->adjvex = i;
e->weight = w;
e->next = G->adjList[j].firstedge; // 头插法
G->adjList[j].firstedge = e;
}
}
int visited[MAX_VERTEX_NUM]; // 访问标志数组
void BFS(Graph G,int v) {
int i,j;
int queue[MAX_VERTEX_NUM],front = 0,rear = 0; // 设置循环队列
EdgeNode *p;
printf("%d ",G.adjList[v].data);
visited[v] = 1;
queue[rear++] = v;
while(front != rear) {
i = queue[front++];
p = G.adjList[i].firstedge;
while(p) {
j = p->adjvex;
if(!visited[j]) {
printf("%d ",G.adjList[j].data);
visited[j] = 1;
queue[rear++] = j;
}
p = p->next;
}
}
}
int main() {
Graph G;
int v;
CreateGraph(&G);
printf("请输入起始遍历的顶点:");
scanf("%d",&v);
printf("广度优先遍历结果:");
BFS(G,v);
return 0;
}
```
希望能够帮到您!
阅读全文