DFS of Graph | Practice | GeeksforGeeks

Given a connected undirected graph. Perform a Depth First Traversal of the graph.
Note: Use recursive approach to find the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph..

Example 1:
Input:

Output: 0 1 2 4 3
Explanation: 
0 is connected to 1, 2, 4.
1 is connected to 0.
2 is connected to 0.
3 is connected to 4.
4 is connected to 0, 3.
so starting from 0, it will go to 1 then 2
then 4, and then from 4 to 3.
Thus dfs will be 0 1 2 4 3.

Example 2:
Input:

Output: 0 1 2 3
Explanation:
0 is connected to 1 , 3.
1 is connected to 2. 
2 is connected to 1.
3 is connected to 0. 
so starting from 0, it will go to 1 then 2
then back to 0 then 0 to 3
thus dfs will be 0 1 2 3. 


Your task:
You dont need to read input or print anything. Your task is to complete the function dfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns  a list containing the DFS traversal of the graph starting from the 0th vertex from left to right according to the graph.

Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

Constraints:
1 ≤ V, E ≤ 104
0
kundan_2508
This comment was deleted.
+1
kharsh82211 hours ago
Java Solution
// { Driver Code Starts
// Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
    public static void main(String[] args) throws IOException {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine().trim());
        while (T-- > 0) {
            String[] s = br.readLine().trim().split(" ");
            int V = Integer.parseInt(s[0]);
            int E = Integer.parseInt(s[1]);
            ArrayList<ArrayList<Integer>> adj =
                new ArrayList<ArrayList<Integer>>();
            for (int i = 0; i < V; i++) adj.add(new ArrayList<Integer>());
            for (int i = 0; i < E; i++) {
                String[] S = br.readLine().trim().split(" ");
                int u = Integer.parseInt(S[0]);
                int v = Integer.parseInt(S[1]);
                adj.get(u).add(v);
                adj.get(v).add(u);
            }
            Solution obj = new Solution();
            ArrayList<Integer> ans = obj.dfsOfGraph(V, adj);
            for (int i = 0; i < ans.size(); i++)
                System.out.print(ans.get(i) + " ");
            System.out.println();
        }
    }
}
// } Driver Code Ends


class Solution {
    // Function to return a list containing the DFS traversal of the graph.
    public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        
        boolean [] visited=new boolean[V];
        
        ArrayList<Integer>[]  list1 =new ArrayList[V];
        
        for (int i = 0; i < V; i++) {
            list1[i] = new ArrayList<Integer>();
        }
        
        for(int i=0;i<adj.size();i++){
            for(int j =0;j<adj.get(i).size();j++){
            list1[i].add(adj.get(i).get(j));
            list1[adj.get(i).get(j)].add(i);
            
            }
             
        }
        
        ArrayList<Integer> list  =new ArrayList<>();
        
        helper(list1,list,visited,0);
        
        return list;
    }
    
    public void helper(ArrayList<Integer>[]  list1,ArrayList<Integer> list ,boolean [] visited,int src){
        visited[src]=true;
        list.add(src);
        
        for(int a :list1[src]){
            if(visited[a]==false){
                helper(list1,list,visited,a);
            }
        }
    }
}
0
thakuraditya6211 day ago
// Function to return a list containing the DFS traversal of the graph.
    public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        ArrayList<Integer> arr = new ArrayList<>();
        boolean[] visited = new boolean [V+1];
        
        for(int i  =0; i < V; i++){
            if(visited[i] == false){
                DFS(adj, arr, visited, i);
            }
        }
        return arr;
    }
    
    void DFS(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> ans, boolean visited[], int src){
        visited[src]  = true;
        ans.add(src);
        
        for(int nbr : list.get(src)){
            if(visited[nbr] == false){
                DFS(list, ans, visited, nbr);
            }
        }
    }
0
indreshgoswami1492 days ago


void dfs(int node, vector<int> &vis, vector<int> adj[], vector<int> &storeDfs) {
        storeDfs.push_back(node); 
        vis[node] = 1; 
        for(auto it : adj[node]) {
            if(!vis[it]) {
                dfs(it, vis, adj, storeDfs); 
            }
        }
    }

public:
    // Function to return a list containing the DFS traversal of the graph.
    vector<int> dfsOfGraph(int V, vector<int> adj[]) {
        // Code here
        vector<int> storeDfs; 
	    vector<int> vis(V+1, 0); 
      for(int i = 1;i<=V;i++) {
        if(!vis[i]) dfs(i, vis, adj, storeDfs); 
      }
	    return storeDfs; 
    }
};


0
deeptimayeemaharana064 days ago
 
WHAT'S THE ERROR IN THIS?
 
void dfs(int node,vector<int>&vis,vector<int>adj[],vector<int>&storedfs){      storedfs.push_back(node);      vis[node]=1;      for(auto it:adj[node])      {          if(!vis[it]){              dfs(it,vis,adj,storedfs);          }      }   }   vector<int> dfsOfGraph(int V,vector<int> adj[])   {        vector<int>dfs;       vector<int> vis(V+1,0);       dfs(0,vis,adj,dfs);              return dfs;   }
 
0
gp9199344 days ago
void Dfsrec(vector<int> adj[],int s,vector<int>&visited){       visited[s]=1;       cout<<s<<" ";       for(auto x:adj[s]){           if(visited[x]==false){               Dfsrec(adj,x,visited);           }       }   }   vector<int> dfsOfGraph(int v, vector<int> adj[]) {       vector<int>visited(v+1,0);       for(int i=0;i<v;i++){           if(visited[i]==false){               Dfsrec(adj,i,visited);           }       }       return {};
}
0
singhdipranjan671 week ago
class Solution {
    // Function to return a list containing the DFS traversal of the graph.
    public ArrayList<Integer> dfsOfGraph(int V, ArrayList<ArrayList<Integer>> list) {
        ArrayList<Integer> brr=new ArrayList<>();
        boolean arr[]=new boolean[V+1];
        for(int i=0; i<V; i++)
        {
            if(arr[i]==false)
            DFSrec(list, brr, arr, i);
        }
    
        return brr;
    }
    void DFSrec(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> brr, boolean arr[], int s)
    {
        arr[s]=true;
        brr.add(s);
        for(int u: list.get(s))
        {
            if(arr[u]==false)
            DFSrec(list, brr, arr, u);
        }
    }
}

0
harshscode1 week ago
o(v+e) and o(v)
 void dfs(int src,vector<int> &v1,vector<int> &vis,vector<int> adj[])      {                                vector<int> r;                      vis[src]=1;                      v1.push_back(src);                                for(auto x:adj[src])                      if(!vis[x])                      dfs(x,v1,vis,adj);         
      }
   vector<int> dfsOfGraph(int v, vector<int> adj[]) {       vector<int> vis(v);       for(int i=0;i<v;i++)       vis[i]=0;       vector<int> v1;        dfs(0,v1,vis,adj);        return v1;          }
0
ajaynikumbh4341 week ago
class Solution 
{
  public:
    void dfs(vector<int> adj[], int i , vector<bool> &v)
    {
        cout<<i<<" ";
        v[i] = true;
        for(auto nbr: adj[i])
        {
            if(!v[nbr])
            {
                dfs(adj, nbr, v);
            }
        }
    }
    
    vector<int> dfsOfGraph(int v, vector<int> adj[])
    {
        vector<bool> visit(v,false);
        for(int i=0;i<v;i++)
        {
            if(!visit[i])
            {
                dfs(adj, i, visit);
            }
        }
        return {};
    }    
};

0
jainmuskan5651 week ago
 vector<int> ans;   void solve(int node, vector<int> adj[],bool visited[]){       visited[node]=true;       ans.push_back(node);       for(int neighbor: adj[node]){           if(!visited[neighbor]){               solve(neighbor,adj,visited);           }       }   }   vector<int> dfsOfGraph(int V, vector<int> adj[]) {       // use recursion and visited array              bool visited[V]={0};       ans.clear();       solve(0,adj,visited);       return ans;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.