Implement the Depth First Search Algorithm in Graph using Simple

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

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

推荐阅读:
让人“又爱又恨”的食品方便面  方便面搭配合理也可以吃得健康  具有保健功效的3种发酵豆制品  世界上最昂贵的10种食物大盘点  营养丰富的西红柿鸡蛋汤两种做法  毛豆膳食纤维含量高这样吃最营养  细说蔬菜甘蓝的四大营养保健价值  饮食与健康:十大抗癌食物排行榜  三款适合秋季食用的润燥养生粥  火锅汤底搭配凉性食材不容易上火 
评论列表
添加评论