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) —
推荐阅读:诗词名句鉴赏:身既死兮神以灵,魂魄毅兮为鬼雄! 诗词名句鉴赏:嘤其鸣矣,求其有声。 数学题:化肥厂计划用15天生产化肥4500吨 数学题:学校把两捆树苗分给三个年级种植 数学题:甲乙丙三人的平均年龄为22岁 数学题:在一块边长60m的正方形花坛四边种冬青树 数学题:用一根铁丝刚好焊成一个棱长10厘米的正方体框架 数学题:一艘船在静水中每小时行驶40千米 数学题:在AB两点之间等距离安装路灯 数学题:一种商品随季节出售
- 评论列表
-
- 添加评论