用C语言建立一个无向图的邻接矩阵表示,实现对图的深度优先
时间: 2024-05-06 10:16:07 浏览: 77
遍历和广度优先遍历。
首先,我们需要定义一个图的数据结构来存储图的信息,包括图中节点的数量和边的数量,以及邻接矩阵。
```c
#define MAX_VERTEX_NUM 100 // 图中节点的最大数量
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储节点的值
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 存储邻接矩阵
int vertex_num; // 节点数量
int edge_num; // 边数量
} Graph;
```
接下来,我们可以实现一个函数来创建一个新的图:
```c
void create_graph(Graph* graph) {
printf("请输入节点数量和边数量(以空格分隔):");
scanf("%d %d", &graph->vertex_num, &graph->edge_num);
printf("请输入所有节点的值(以空格分隔):");
for (int i = 0; i < graph->vertex_num; i++) {
scanf("%d", &graph->vertex[i]);
}
printf("请输入每条边的两个节点的下标(以空格分隔):\n");
for (int i = 0; i < graph->edge_num; i++) {
int x, y;
scanf("%d %d", &x, &y);
graph->edge[x][y] = 1;
graph->edge[y][x] = 1;
}
}
```
现在,我们可以实现深度优先遍历和广度优先遍历。深度优先遍历使用递归实现,广度优先遍历使用队列实现。
```c
void dfs(Graph* graph, int visited[], int index) {
visited[index] = 1;
printf("%d ", graph->vertex[index]);
for (int i = 0; i < graph->vertex_num; i++) {
if (graph->edge[index][i] && !visited[i]) {
dfs(graph, visited, i);
}
}
}
void bfs(Graph* graph, int visited[], int index) {
int queue[MAX_VERTEX_NUM];
int front = 0, rear = 0;
queue[rear++] = index;
visited[index] = 1;
while (front < rear) {
int curr_index = queue[front++];
printf("%d ", graph->vertex[curr_index]);
for (int i = 0; i < graph->vertex_num; i++) {
if (graph->edge[curr_index][i] && !visited[i]) {
visited[i] = 1;
queue[rear++] = i;
}
}
}
}
```
最后,我们可以编写一个主函数来测试我们的代码:
```c
int main() {
Graph graph;
create_graph(&graph);
int visited[MAX_VERTEX_NUM] = {0};
printf("深度优先遍历结果:");
for (int i = 0; i < graph.vertex_num; i++) {
if (!visited[i]) {
dfs(&graph, visited, i);
}
}
printf("\n");
memset(visited, 0, sizeof visited);
printf("广度优先遍历结果:");
for (int i = 0; i < graph.vertex_num; i++) {
if (!visited[i]) {
bfs(&graph, visited, i);
}
}
printf("\n");
return 0;
}
```
阅读全文