Implement the Depth First Search Algorithm in Graph using Simple

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

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

推荐阅读:
如何获取wordpress外循环的自定义栏目  为wordpress媒体文件添加分类目录和标签的方法  小技巧:在wordpress仪表盘中双击评论内容可编辑评论  解决wordpress自动更新失败无法进入后台的方法及升级失败原因  通过.htaccess限制访问IP 保护wordpress后台安全  第一次坐公交车作文100字  人生思考作文800字  上海东方明珠塔作文400字  冬日趣事作文100字  妈妈母亲节快乐作文300字 
评论列表
添加评论