用C语言写一个广度优先遍历和深度优先遍历
时间: 2023-10-19 14:07:55 浏览: 84
广度优先遍历和深度优先遍历是常见的遍历算法,下面是用 C 语言写的示例代码:
广度优先遍历:
```c
#include <stdio.h>
#define MAX_QUEUE_SIZE 100
int graph[MAX_QUEUE_SIZE][MAX_QUEUE_SIZE];
int visited[MAX_QUEUE_SIZE] = {0};
int queue[MAX_QUEUE_SIZE];
int front = -1, rear = -1;
void bfs(int start, int n) {
visited[start] = 1;
queue[++rear] = start;
while (front != rear) {
int u = queue[++front];
printf("%d ", u);
for (int v = 0; v < n; v++) {
if (graph[u][v] && !visited[v]) {
visited[v] = 1;
queue[++rear] = v;
}
}
}
}
int main() {
int n, start;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex: ");
scanf("%d", &start);
printf("BFS traversal: ");
bfs(start, n);
return 0;
}
```
深度优先遍历:
```c
#include <stdio.h>
#define MAX_STACK_SIZE 100
int graph[MAX_STACK_SIZE][MAX_STACK_SIZE];
int visited[MAX_STACK_SIZE] = {0};
int stack[MAX_STACK_SIZE];
int top = -1;
void dfs(int start, int n) {
visited[start] = 1;
stack[++top] = start;
printf("%d ", start);
for (int v = 0; v < n; v++) {
if (graph[start][v] && !visited[v]) {
dfs(v, n);
}
}
top--;
}
int main() {
int n, start;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex: ");
scanf("%d", &start);
printf("DFS traversal: ");
dfs(start, n);
return 0;
}
```
希望这可以帮助你理解广度优先遍历和深度优先遍历的算法。
阅读全文