深度优先搜索算法C语言
时间: 2023-11-14 09:06:27 浏览: 129
深度优先搜索(Depth First Search,DFS)是一种图遍历算法,用于遍历或搜索树或图的所有节点。下面是一个使用C语言实现的简单深度优先搜索算法的示例:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
bool visited[MAX_SIZE];
typedef struct {
int vertices[MAX_SIZE];
int top;
} Stack;
void push(Stack *stack, int vertex) {
stack->vertices[++(stack->top)] = vertex;
}
int pop(Stack *stack) {
return stack->vertices[(stack->top)--];
}
bool isStackEmpty(Stack *stack) {
return stack->top == -1;
}
void dfs(int graph[MAX_SIZE][MAX_SIZE], int start, int numVertices) {
Stack stack;
stack.top = -1;
for (int i = 0; i < numVertices; i++) {
visited[i] = false;
}
push(&stack, start);
visited[start] = true;
while (!isStackEmpty(&stack)) {
int currentVertex = pop(&stack);
printf("%d ", currentVertex);
for (int i = 0; i < numVertices; i++) {
if (graph[currentVertex][i] == 1 && !visited[i]) {
push(&stack, i);
visited[i] = true;
}
}
}
}
int main() {
int numVertices, start;
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
int graph[MAX_SIZE][MAX_SIZE];
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
scanf("%d", &graph[i][j]);
}
}
printf("Enter the starting vertex: ");
scanf("%d", &start);
printf("Depth First Traversal: ");
dfs(graph, start, numVertices);
return 0;
}
```
阅读全文