您的位置:首页 > 房产 > 家装 > 18 C语言实现深度优先搜索

18 C语言实现深度优先搜索

2024/11/9 9:40:02 来源:https://blog.csdn.net/qq_35061546/article/details/142189681  浏览:    关键词:18 C语言实现深度优先搜索
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"#define MaxVertex 10typedef char ElemType;typedef struct Node { //链表中的值int nextVertex;//指向的位置struct Node *next;
} Node;struct HeadNode {//链表头ElemType data;struct Node *next;
};typedef struct AdjacencyGraph {int vertexCount;//顶点数int edgeCount;//边数struct HeadNode vertex[MaxVertex];//顶点数组
} Graph;Graph *create_graph() {Graph *graph = (Graph *) malloc(sizeof(Graph));if (graph == NULL) {exit(-1);}graph->vertexCount = 0;graph->edgeCount = 0;return graph;
}void insert_vertex(Graph *graph, ElemType data) {if (graph->vertexCount >= MaxVertex) {return;}graph->vertex[graph->vertexCount].data = data;graph->vertex[graph->vertexCount].next = NULL;graph->vertexCount++;
}void insert_edge(Graph *graph, int a, int b) {Node *node = graph->vertex[a].next;Node *newNode = malloc(sizeof(struct Node));newNode->next = NULL;newNode->nextVertex = b;if (node == NULL) {graph->vertex[a].next = newNode;} else {do {if (node->nextVertex == b) {free(newNode);break;}if (node->next) {node = node->next;} else {break;}} while (1);node->next = newNode;}graph->edgeCount++;
}void printGraph(Graph *graph) {for (int i = 0; i < graph->vertexCount; ++i) {printf("%d | %c", i, graph->vertex[i].data);Node *node = graph->vertex[i].next;while (node) {printf(" -> %d", node->nextVertex);node = node->next;}putchar('\n');}
}/*** 深度优先搜索* @param graph 图* @param start 开始顶点* @param target 结束顶点* @param visited 已经访问过的内容* @return*/
bool dfs(Graph *graph, int start, int target, int *visited) {printf("%c -> ", graph->vertex[start].data);visited[start] = 1;if (start == target) {return true;}Node *node = graph->vertex[start].next;while (node) {if (visited[node->nextVertex] == 0) {if (dfs(graph, node->nextVertex, target, visited)) {return true;}}node = node->next;}return false;
}int main() {setbuf(stdout, NULL);Graph *graph = create_graph();for (int i = 'A'; i <= 'F'; ++i) {insert_vertex(graph, (char) i);}insert_edge(graph, 0, 1);//A->Binsert_edge(graph, 1, 2);//B->Cinsert_edge(graph, 1, 3);//B->Dinsert_edge(graph, 1, 4);//B->Einsert_edge(graph, 4, 5);//E->FprintGraph(graph);int arr[graph->vertexCount];for (int i = 0; i < graph->vertexCount; ++i) {arr[i] = 0;}printf("\n%d ", dfs(graph, 0, 5, arr));free(graph);return 0;
}

运行效果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com