c++采用深度优先算法和广度优先遍历算法遍历图
时间: 2023-11-10 10:13:51 浏览: 105
C语言可以使用深度优先搜索和广度优先搜索算法来遍历图。下面是用C语言实现深度优先搜索和广度优先搜索的示例代码:
深度优先搜索:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct {
int vertices[MAX_VERTICES][MAX_VERTICES];
int n;
} Graph;
int visited[MAX_VERTICES];
void dfs(Graph* graph, int vertex) {
int i;
visited[vertex] = 1;
printf("%d ", vertex);
for (i = 0; i < graph->n; i++) {
if (graph->vertices[vertex][i] && !visited[i]) {
dfs(graph, i);
}
}
}
int main() {
Graph graph;
int i, j;
scanf("%d", &graph.n);
for (i = 0; i < graph.n; i++) {
visited[i] = 0;
for (j = 0; j < graph.n; j++) {
graph.vertices[i][j] = 0;
}
}
// 读入图的边
int u, v;
while (scanf("%d%d", &u, &v) == 2) {
graph.vertices[u][v] = 1;
}
// 深度优先搜索遍历图
for (i = 0; i < graph.n; i++) {
if (!visited[i]) {
dfs(&graph, i);
}
}
return 0;
}
```
广度优先搜索:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
typedef struct {
int vertices[MAX_VERTICES][MAX_VERTICES];
int n;
} Graph;
int visited[MAX_VERTICES];
void bfs(Graph* graph, int vertex) {
int i, queue[MAX_VERTICES], front = 0, rear = 0;
visited[vertex] = 1;
printf("%d ", vertex);
queue[rear++] = vertex;
while (front < rear) {
int v = queue[front++];
for (i = 0; i < graph->n; i++) {
if (graph->vertices[v][i] && !visited[i]) {
visited[i] = 1;
printf("%d ", i);
queue[rear++] = i;
}
}
}
}
int main() {
Graph graph;
int i, j;
scanf("%d", &graph.n);
for (i = 0; i < graph.n; i++) {
visited[i] = 0;
for (j = 0; j < graph.n; j++) {
graph.vertices[i][j] = 0;
}
}
// 读入图的边
int u, v;
while (scanf("%d%d", &u, &v) == 2) {
graph.vertices[u][v] = 1;
}
// 广度优先搜索遍历图
for (i = 0; i < graph.n; i++) {
if (!visited[i]) {
bfs(&graph, i);
}
}
return 0;
}
```
阅读全文