Implement the Depth First Search Algorithm in Graph using Simple
- 时间:2020-09-19 10:45:07
- 分类:网络文摘
- 阅读:117 次
Given a graph represented by G(V, E) where V is the vertices and E represents the edges, we can do a Depth First Search Algorithm (DFS) on any node/vertex. The DFS will mark the current node visited and visit the node using using the (*visit) function (C++ function pointer), and recursively call itself with the connected edges.
1 2 3 4 5 6 7 8 9 10 | void traverseDepthFirstSearch(int node, void(*visit)(int)) { link t; (*visit)(k); visited[k] = 1; // mark the node as visited for (t = adj[k]; t != NULL; t = t->next) { if (!visited[t->v]) { // avoid cycle traverseDepthFirstSearch(t->v, visit); } } } |
void traverseDepthFirstSearch(int node, void(*visit)(int)) {
link t;
(*visit)(k);
visited[k] = 1; // mark the node as visited
for (t = adj[k]; t != NULL; t = t->next) {
if (!visited[t->v]) { // avoid cycle
traverseDepthFirstSearch(t->v, visit);
}
}
}
three-nodes
The algorithimic complexity is O(N) where N is the number of nodes connected to the given vertex. The space complexity is also O(N).
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:南瓜的保健作用:降血糖血脂、防癌 大暑养生:暑天应多吃清淡易消化食物 市场热俏的功能性饮料到底是什么? 不能把功能性饮料完全代替饮用水 功能性饮料应该如何科学合理的饮用 网传的10种致癌食物中有9种不靠谱 夏季常见水果:西瓜的营养保健价值 健康食品黑枣的食疗功效与营养价值 保健食品当做药品卖“脑力风暴”骗局 “公益网站”牵线 保健食品当药品卖
- 评论列表
-
- 添加评论