当前位置: 首页 > news >正文

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;
}

运行效果


http://www.mrgr.cn/news/25787.html

相关文章:

  • 介绍 Apache Spark 的基本概念和在大数据分析中的应用。
  • OpenAI发布最强推理模型o1,它真的会思考,但API比4o贵好几倍
  • VMware替换需重点关注这件事,可能直接影响迁移的成败
  • AI图像篡改检测:如何识破Deepfake的虚假伪装?
  • 自己掏耳朵怎么弄干净?可视挖耳勺排行榜!
  • linux入门到实操-4 linux系统网络配置、连接测试、网络连接模式、修改静态IP、配置主机名
  • 惠海升压恒流芯片ICH6901B支持2.7V3.7V升12V24V36V48V60V100V调光无频闪 300W大功率应急灯
  • 家庭期待与学业重压:青少年心理健康的双重挑战
  • ️ 保护您的 JavaScript:安全和隐私的最佳实践
  • 稀土长余辉发光剂能让玩具发光吗?
  • 揭秘!守护大脑健康,远离帕金森的七大黄金法则
  • STM32+FATFS+SD卡+RTC(生成.CSV格式文件)
  • Linux(4)--CentOS8虚拟机下联网
  • JAVA学习-练习试用Java实现“将数据流变为多个不相交区间”
  • 决策树算法的介绍与应用
  • 5 存储器
  • 「2.1」前缀后缀——字符串哈希
  • 使用实时编辑器任务清理杂乱数据并定位极值
  • mysql DBA常用的sql
  • AttributeError: module ‘numpy‘ has no attribute ‘object‘.