c语言实现图的深度优先遍历和广度优先遍历算法。
时间: 2023-10-04 15:10:44 浏览: 99
掌握图的两种遍历算法深度优先搜索和广度优先搜索算.pdf
深度优先遍历(DFS)和广度优先遍历(BFS)是图的两种常见遍历算法。下面是使用C语言实现DFS和BFS的示例代码。
假设图用邻接表存储,每个节点的邻接点用链表表示。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 100
typedef struct node {
int v; // 邻接点的编号
struct node *next;
} node_t;
typedef struct graph {
int n; // 节点个数
node_t *adj[MAX_N]; // 邻接表
} graph_t;
// 深度优先遍历
void dfs(graph_t *g, int v, int visited[]) {
printf("%d ", v);
visited[v] = 1;
node_t *p = g->adj[v];
while (p) {
if (!visited[p->v]) {
dfs(g, p->v, visited);
}
p = p->next;
}
}
// 广度优先遍历
void bfs(graph_t *g, int v, int visited[]) {
int queue[MAX_N], head = 0, tail = 0;
queue[tail++] = v;
visited[v] = 1;
while (head < tail) {
int u = queue[head++];
printf("%d ", u);
node_t *p = g->adj[u];
while (p) {
if (!visited[p->v]) {
visited[p->v] = 1;
queue[tail++] = p->v;
}
p = p->next;
}
}
}
int main() {
int n, m, i, u, v;
graph_t *g = (graph_t*) malloc(sizeof(graph_t));
scanf("%d%d", &n, &m);
// 初始化图
g->n = n;
for (i = 0; i < n; i++) {
g->adj[i] = NULL;
}
// 读入边
for (i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
node_t *p = (node_t*) malloc(sizeof(node_t));
p->v = v;
p->next = g->adj[u];
g->adj[u] = p;
p = (node_t*) malloc(sizeof(node_t));
p->v = u;
p->next = g->adj[v];
g->adj[v] = p;
}
// 深度优先遍历
int visited[MAX_N] = {0};
dfs(g, 0, visited);
printf("\n");
// 广度优先遍历
for (i = 0; i < n; i++) {
visited[i] = 0;
}
bfs(g, 0, visited);
printf("\n");
// 释放内存
for (i = 0; i < n; i++) {
node_t *p = g->adj[i];
while (p) {
node_t *tmp = p;
p = p->next;
free(tmp);
}
}
free(g);
return 0;
}
```
输入格式为:
```
节点个数 边数
边1起点 边1终点
边2起点 边2终点
...
```
例如:
```
4 3
0 1
1 2
2 3
```
输出为:
```
0 1 2 3
0 1 2 3
```
阅读全文