Advertisement
i_love_rao_khushboo

Untitled

Aug 9th, 2022
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. void dfsHelper(T src, unordered_map<T, bool> &visited, vector<T> &r)
  2. {
  3. //marking a node visited as soon as it is pushed in
  4. //internal call stack
  5. visited[src]=true;
  6.  
  7. //push src in the result
  8. r.push_back(src);
  9.  
  10. //go to all the unvisited nodes of the current
  11. //node, but one by one
  12. for(auto x: mp[src])
  13. {
  14. //check if already visited or not
  15. if(!visited[x])
  16. {
  17. //push it in the stack(internal call stack is used)
  18. dfsHelper(x, visited, r);
  19. }
  20. }
  21. }
  22.  
  23. int dfs(T src)
  24. {
  25. //to store one of the many possible dfs traversal,
  26. //using any vertex as source(starting vertex)
  27. vector<T> r;
  28.  
  29. //to check if a vertex isVisited
  30. unordered_map<T, bool> visited;
  31.  
  32. int count=0; // to store the count of connected compo.
  33. for(auto p: mp)
  34. {
  35. if(!visited[p.first])
  36. {
  37. cnt++;
  38.  
  39. //helper function
  40. dfsHelper(p.first, visited, r);
  41. }
  42. }
  43.  
  44. return count;
  45. }
  46.  
  47. // NOTE: The same result can also be achieved using BFS also.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement