Implement the Depth First Search Algorithm in Graph using Simple

  • 时间:2020-09-19 10:45:07
  • 分类:网络文摘
  • 阅读:122 次

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 Implement the Depth First Search Algorithm in Graph using Simple C/C++ algorithms c / c++ DFS graph

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) —

推荐阅读:
数学题:回收1千克废纸,可生产0.8千克再生纸  数学题:丢番图的墓志铭  数学题:如果一个圆柱体的底面直径与高相等  数学题:卧车和客车所行路程比15:16  要将糖和水按5:100的比配制成糖水  数学题:一个长方体木块与一个正方体木块刚好可以拼成一个大长方体木块  数学题:如果每间5人,则有14人没床位  都是马虎惹的祸作文400字  美中不足  诗酒永相随(文/白水先生) 
评论列表
添加评论