Depth First Traversal for a Graph

PROBLEM :
Write a function to print the depth first traversal for a graph from a given source s.

Input:
The task is to complete the function DFS which takes 3 arguments an integer denoting the starting node (s) of the dfs travel , a  graph (g)  and an array of visited nodes (vis)  which are initially all set to false .
There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should print the depth first traversal for the graph from the given source.

Note : The expected output button always produces DFS starting from node 1.

Constraints:
1 <=T<= 100
1 <=Number of  edges<= 100

Example:
Input:
1
4
1 2 1 3 1 4 3 5

Output:
1 2 3 5 4    //dfs from node 1

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* You have to complete this function
which prints out the depth first level traversal of the
graph starting from node s
the vector<int> g[i] represent the adjacency
list of the ith node of the graph
 */

void dfs(int s, vector<int> g[], bool vis[])
{
    vis[s]=true ;
    cout<<s<<" " ;
   
    vector<int>::iterator i ;
    for(i=g[s].begin();i!=g[s].end();i++)
    {
        if(vis[*i]==false)
            dfs(*i,g,vis) ;
    }
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )