图——深度优先搜索(Graph - Depth First Search)

深度优先搜索(DFS)是一种遍历或搜索树或图数据结构的算法。从根节点开始(对于图来说,选择任意节点作为根),沿着每个分支尽可能深入地探索,再回溯。本文介绍了DFS的基本概念、示例、使用栈进行遍历的过程、搜索树的绘制,以及DFS的时间复杂度。同时,探讨了如何利用DFS解决图是否连通、是否存在环以及如何判断有向无环图等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


简介(Introduction)
Depth-first search(DFS) is an algorithm for traversing or searching tree or graph data structure. One starts at the root(selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

示例(Example)
这里写图片描述
DFS order: a, b, d, e, c, f, g.

检索栈(The Traversal Stack)
We can use a traversal stack to track where we are in overall process.

的深度优先遍历(Depth-First Search, DFS)是一种用于遍历或搜索树或算法。它会尽可能深地搜索的分支,直到找到目标节点或遍历完所有节点。邻接表是一种常用的表示方法,特别适用于稀疏。 下面是一个使用邻接表实现深度优先遍历的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> // 定义邻接表的节点结构 typedef struct AdjListNode { int dest; struct AdjListNode* next; } AdjListNode; // 定义的结构 typedef struct Graph { int numVertices; AdjListNode** adjLists; } Graph; // 创建一个新的邻接表节点 AdjListNode* createAdjListNode(int dest) { AdjListNode* newNode = (AdjListNode*)malloc(sizeof(AdjListNode)); newNode->dest = dest; newNode->next = NULL; return newNode; } // 创建 Graph* createGraph(int numVertices) { Graph* graph = (Graph*)malloc(sizeof(Graph)); graph->numVertices = numVertices; // 为邻接表数组分配内存 graph->adjLists = (AdjListNode**)malloc(numVertices * sizeof(AdjListNode*)); // 初始化每个邻接表为空 for (int i = 0; i < numVertices; i++) { graph->adjLists[i] = NULL; } return graph; } // 向中添加边 void addEdge(Graph* graph, int src, int dest) { // 从源节点到目标节点 AdjListNode* newNode = createAdjListNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; // 从目标节点到源节点(如果是无向) newNode = createAdjListNode(src); newNode->next = graph->adjLists[dest]; graph->adjLists[dest] = newNode; } // 深度优先遍历的辅助函数 void DFSUtil(Graph* graph, int vertex, bool* visited) { visited[vertex] = true; printf("%d ", vertex); AdjListNode* adjList = graph->adjLists[vertex]; while (adjList != NULL) { int adjVertex = adjList->dest; if (!visited[adjVertex]) { DFSUtil(graph, adjVertex, visited); } adjList = adjList->next; } } // 深度优先遍历 void DFS(Graph* graph, int startVertex) { bool* visited = (bool*)malloc(graph->numVertices * sizeof(bool)); for (int i = 0; i < graph->numVertices; i++) { visited[i] = false; } DFSUtil(graph, startVertex, visited); free(visited); } // 主函数 int main() { int numVertices = 5; Graph* graph = createGraph(numVertices); addEdge(graph, 0, 1); addEdge(graph, 0, 4); addEdge(graph, 1, 2); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 3); addEdge(graph, 3, 4); printf("深度优先遍历结果: "); DFS(graph, 0); return 0; } ``` 这个示例代码展示了如何使用邻接表实现的深度优先遍历。代码中定义了一个的结构,并实现了创建、添加边和深度优先遍历的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值