first init
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define MAX_VERTICES 5 // 图的最大顶点数
|
||||
|
||||
// 图的邻接矩阵表示
|
||||
int graph[MAX_VERTICES][MAX_VERTICES] = {
|
||||
{0, 1, 1, 0, 0},
|
||||
{1, 0, 1, 1, 0},
|
||||
{1, 1, 0, 0, 1},
|
||||
{0, 1, 0, 0, 1},
|
||||
{0, 0, 1, 1, 0}
|
||||
};
|
||||
|
||||
bool visited[MAX_VERTICES]; // 访问标记数组,用来记录哪些节点已经被访问过
|
||||
|
||||
// 深度优先遍历 DFS 函数
|
||||
void dfs(int v, int n) {
|
||||
printf("%d ", v); // 输出当前节点
|
||||
visited[v] = true; // 标记当前节点已访问
|
||||
|
||||
// 递归访问当前节点的所有未访问的邻接节点
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (graph[v][i] == 1 && !visited[i]) { // 如果存在边且该邻接节点未被访问
|
||||
dfs(i, n); // 递归调用,访问该邻接节点
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int n = MAX_VERTICES; // 图的顶点数
|
||||
for (int i = 0; i < n; i++) {
|
||||
visited[i] = false; // 初始化访问标记数组,将所有节点标记为未访问
|
||||
}
|
||||
|
||||
printf("深度优先遍历(DFS):\n");
|
||||
dfs(0, n); // 从顶点 0 开始进行 DFS 遍历
|
||||
printf("\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user