Titanium_Owner's blog

By Titanium_Owner, history, 4 months ago, In English,

simple dfs code.... why is it not working? please help input : 6 1 1 6 1 2 2 3 2 5 3 4 4 5 code : http://pastebin.com/EazYw5af my code run properly when I remove printf which is out of for loop in dfs function. If I write printf function... it does not work... strange..

 
 
 
 
  • Vote: I like it  
  • -7
  • Vote: I do not like it  

»
4 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Because It's underfined behaviour. printf("%d %d\n",x,visited[G[x][k]]); At this line, k = G[x].size() because of end of loop.

  • »
    »
    4 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    It is not working when prinf is inside the loop outside the if statement. for(k=0; k<G[x].size(); k++) { if(visited[G[x][k]]==0) { visited[G[x][k]]=1;

    int v=G[x][k];
            //  cout<<v<<endl;
            dfs(v);
        }
    
        printf("%d %d\n",x,visited[G[x][k]]);
    }
    • »
      »
      »
      4 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Make 'k' not global. Also don't use global variables at all.

      • »
        »
        »
        »
        4 months ago, # ^ |
        Rev. 2   Vote: I like it +13 Vote: I do not like it

        In real world programming using global variables is bad. But in competitive programming it usually improves working time of the solution and can be crucial. So I am not sure, if "don't use global variables at all" is good advice for competitive programming.

    • »
      »
      »
      4 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      inside DFS or any backtracking code do not use GLOBAL VARIABLE loop variables ( for(k=0;k<...) . It will cause mulfunction .

»
4 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Thank you everyone for your response