How to maintain values in recursive calls?

657 views Asked by At

Let us su[ppose,we have a bidirectional graph as shown below

enter image description here

Now, it's DFS Traversal from source 8 will be 8 1 2 3 6 7 4 5. The recursive implementation

vector <int>  v[10001];
bool visited[10001];
void DFS(int s)
{
 visited[s]=true;
 cout<<s<<" ";
 for(int i=0;i<v[s].size();i++)
 {

 if(!visited[v[s][i]])
 {
     DFS(v[s][i]);
 }
 }
}

So first it will recursively go as 8->1->2->3 , 8->6 , 8->7->4->5

Now,using this function, i also want to keep the track of distance of every node from it's source. Let us call this as dist[N] where N=number of nodes. In this graph dist[8]=0, dist1=1, dist[2]=2 and so on. How can i implement this?

At first i tried keeping a variable d and incrementing it as shown in the code below

int d=0;
void DFS(int s)
{
 visited[s]=true;
 cout<<s<<" ";
 dist[s]=d;
 d++;
 for(int i=0;i<v[s].size();i++)
 {
 if(!visited[v[s][i]])
 {
     DFS(v[s][i]);
 }
 }
}

But obviously,the value of d has to be reset to 0 when it reaches 8 again ,other wise dist[6] will be 1+ dist[3] according to above function . How to overcome this ? Also , is there some more efficient way to achieve this?

1

There are 1 answers

0
MuertoExcobito On BEST ANSWER

Instead of having a global variable tracking depth, it can be a parameter to the next iteration.

void DFS(int s, int d)
{
 visited[s]=true;
 cout<<s<<" ";
 dist[s]=d;
 for(int i=0;i<v[s].size();i++)
 {
     if(!visited[v[s][i]])
    {
       DFS(v[s][i], d+1);
    }
 }
}