0
void dfs(int a, int virus)
{
    visited[a] =1;
   
    for(int i =1; i <= virus; i++)
    {
       
        if(comp[a][i])
        {
          
             a = i; 
            if(!visited[a]){
                dfs(a,virus);
            }
        }
    }
}

Why doesn't it work properly when I use it like this without declaring the variable? please teach me ... im so struggling with this

#include <stdio.h>

#define max 101
int com,virus;
int comp[max][max];
int visited[max] ={0,};

void dfs(int a, int virus)
{
    visited[a] =1;
   
    for(int i =1; i <= virus; i++)
    {
        int y;
        if(comp[a][i])
        {
          
             y = i; // ->> if I just use (a = i) instead of declaring a variable(y) 
          //such as a = i
             //if(!visited[a]){
                //dfs(a,virus);
                //}
            if(!visited[y]){
                dfs(y,virus);
            }
        }
    }
}

int main()
{
    scanf("%d",&com);
    scanf("%d",&virus);

    for(int i =0; i< virus; i++)
    {
        int a,b;
        scanf("%d %d",&a,&b);

        comp[a][b] = 1;
        comp[b][a] = 1;
    }
    dfs(1,7);
    
  
}

if I just use (a = i) instead of declaring a variable(y) why is dfs not working ?
for example 7 6 1 2 2 3 1 5 5 2 5 6 4 7 What are the reasons? this supposed to be 1 2 3 5 6 but it stopped after 3

  • 2
    C and C++ are two different languages. Please tag the one you are using. And please explain what you mean with "not working" – 463035818_is_not_an_ai Mar 20 '23 at 09:12
  • consider what will be the value of `a` in the next iteration of the inner loop for the two versions of the code. – 463035818_is_not_an_ai Mar 20 '23 at 09:23
  • Consider the difference between "tell each of my neighbours to do a DFS while I wait here" and "I move to one of my neighbours and do a DFS from there, then I move to one of its neighbours and do a DFS from there, ..." – molbdnilo Mar 20 '23 at 12:37
  • Om a side note, `y` is unnecessary and only confuses; `if (!visited[i]) { dfs(i, virus); }` is better. – molbdnilo Mar 20 '23 at 12:38

0 Answers0