# 算法与数据结构 图

1.建立任意无向图，采用邻接矩阵存储，输出该图的深度优先遍历序列。2.建立任意无向图，采用邻接矩阵存储，输出该图的广度优先遍历序列。

#include <stdio.h>
typedef struct {
int vertexnum;
int edgenum;
int vertex[100];
int edge[100][100];
int visited[100];
} MGraph;
void initGraph(MGraph* G, int a[], int n, int e) {
int i, j, k, u, v;
G->vertexnum = n;
G->edgenum = e;

for (i = 0; i < G->vertexnum; i++) {
G->vertex[i] = a[i];
G->visited[i] = 0;
for (j = 0; j < G->vertexnum; j++) { // 初始化邻接矩阵为0
G->edge[i][j] = 0;
}
}
for (k = 0; k < G->edgenum; k++) {
printf("Enter the two vertices for edge %d (separated by a space): ", k + 1);
scanf_s("%d %d", &u, &v); // 使用标准的scanf函数
if (u < 0 || u >= G->vertexnum || v < 0 || v >= G->vertexnum) {
printf("Invalid vertex number!\n");
return; // 或者你可以选择忽略无效的边
}
G->edge[u][v] = 1;
G->edge[v][u] = 1; // 无向图，双向连接
}
}
void DFTraverse(MGraph* G, int v) {
printf("%d ", G->vertex[v]);
G->visited[v] = 1;
for (int j = 0; j < G->vertexnum; j++) {
if (G->edge[v][j] == 1 && G->visited[j] == 0) {
DFTraverse(G, j);
}
}
}
void BFTraverse(MGraph* G, int v) {
int w, j, Q[100];
int front = 0, rear = 0;
printf("%d ", G->vertex[v]);
G->visited[v] = 1;
Q[rear++] = v;
while (front != rear) {
w = Q[front++];
for (j = 0; j < G->vertexnum; j++) {
if (G->edge[w][j] == 1 && G->visited[j] == 0) {
printf("%d ", G->vertex[j]);
G->visited[j] = 1;
Q[rear++] = j;
}
}
}
}
int main() {
MGraph G;
int vertices[] = { 0, 1, 2, 3 };
int numvertices = 4;
int numedges = 5;
initGraph(&G, vertices, numvertices, numedges);
for (int i = 0; i < G.vertexnum; i++) {
for (int j = 0; j < G.vertexnum; j++) {
printf("%d ", G.edge[i][j]);
}
printf("\n");
}
printf("\nDepth-First Traversal: ");
DFTraverse(&G, 0);
printf("\n");
// 重置visited数组以进行广度优先遍历
for (int i = 0; i < G.vertexnum; i++) {
G.visited[i] = 0;
}
BFTraverse(&G, 0);
printf("\n");
return 0;
}

• 9
点赞
• 0
收藏
觉得还不错? 一键收藏
• 2
评论

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。