Advertisement
vaibhav1906

DFS Solution

Jul 27th, 2021
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. //Link to the question : https://practice.geeksforgeeks.org/problems/depth-first-traversal-for-a-graph/1
  2.  
  3. void dfs(vector<int> adj[],vector<bool> &visit,vector<int> &ans, int curr){
  4.  
  5. visit[curr] = true;
  6. ans.push_back(curr);
  7.  
  8. for(int i = 0; i<adj[curr].size() ; i++){
  9. int ncurr = adj[curr][i];
  10.  
  11. if(visit[ncurr]==false){
  12. dfs(adj,visit,ans,ncurr);
  13. }
  14.  
  15. }
  16.  
  17. return;
  18. }
  19. class Solution
  20. {
  21. public:
  22. //Function to return a list containing the DFS traversal of the graph.
  23. vector<int>dfsOfGraph(int V, vector<int> adj[])
  24. {
  25. // Code here
  26. vector<bool> visit (V,false);
  27. vector<int> ans;
  28.  
  29. dfs(adj,visit,ans,0);
  30.  
  31. return ans;
  32.  
  33. }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement