Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void dfsHelper(T src, unordered_map<T, bool> &visited, vector<T> &r)
- {
- //marking a node visited as soon as it is pushed in
- //internal call stack
- visited[src]=true;
- //push src in the result
- r.push_back(src);
- //go to all the unvisited nodes of the current
- //node, but one by one
- for(auto x: mp[src])
- {
- //check if already visited or not
- if(!visited[x])
- {
- //push it in the stack(internal call stack is used)
- dfsHelper(x, visited, r);
- }
- }
- }
- int dfs(T src)
- {
- //to store one of the many possible dfs traversal,
- //using any vertex as source(starting vertex)
- vector<T> r;
- //to check if a vertex isVisited
- unordered_map<T, bool> visited;
- int count=0; // to store the count of connected compo.
- for(auto p: mp)
- {
- if(!visited[p.first])
- {
- cnt++;
- //helper function
- dfsHelper(p.first, visited, r);
- }
- }
- return count;
- }
- // NOTE: The same result can also be achieved using BFS also.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement