Implement the Depth First Search Algorithm in Graph using Simple

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

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

推荐阅读:
8 Ways to Build Up Seed Money to Turn Your Blog into a Business  Apple Reveals ARKit At WWDC  Blogging From the Road: Japan Edition  How to Redesign Your Blog for Improved User Experience  Yes, It’s Possible to Grab Loans When Working as a Freelancer  2017 Most Unique and Friendliest CMS for Small Businesses  5 Easy Steps to Writing the Perfect Guest Post  A Compilation of the Best Content Creation Strategies from 43 Ex  Why Writing Internships Are an Underrated Way to Become a Great   Compute Number of Lines To Write String (Wordwrap) 
评论列表
添加评论