title: Terminated due to timeout? How to improve DFS
body: <p>I tried a hackerrank problem <a href="https://www.hackerrank.com/challenges/journey-to-the-moon" rel="nofollow noreferrer">link</a> and that gives me terminated due to time out for 3 test case. There I used a dfs method to check for the connected components and get the ans using sum of products of each disjoint elements.(a<em>b + a</em>c + a<em>d + b</em>c + b<em>d + c</em>d == a*b + (a+b)*c + (a+b+c)*d). I need to know what's wrong with my dfs ;{( and how can I improve this. I need not to have a solution to the hackerrank problem. Just need to know what are my mistakes.</p>
  
  <p>Here's my code. Thanks</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  #define For(i,a,n) for (int i=a; i&lt;n; i++)
  typedef vector&lt;int&gt; vi;
  
  // returns no. of connected nodes to a given node
  int connected(int node, vector&lt;vi&gt; adj, bool visited[]){
      int count = 0;
      for(auto x: adj[node]){
          if(visited[x]) continue;
          visited[x] = true;
          count += connected(x, adj, visited) + 1;
      }
      return count;
  }
  
  void dfs(int nodes, vector&lt;vi&gt; adj, bool visited[]){
      int ans = 0;
      visited[nodes] = true;
      int current_sum = connected(nodes, adj, visited) + 1;
  
      while(nodes--){
          if(visited[nodes]) continue;
          visited[nodes] = true;
          int out = connected(nodes, adj, visited) + 1;
          ans += current_sum*out;
          current_sum += out;    
      }
      cout&lt;&lt; ans;
  }
  
  int main() {
      ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  
      int a,b,edges,nodes;
      cin&gt;&gt;nodes&gt;&gt;edges;
      bool visited[nodes];
      fill(visited, visited + nodes, 0);
      vector&lt;vi&gt; adj(nodes);
  
      // adj[i] gives the directly connected nodes to i
      while(edges--){
          cin&gt;&gt;a&gt;&gt;b;
          adj[a].push_back(b);
          adj[b].push_back(a);
      }
  
      dfs(nodes-1, adj, visited);
      return 0;
  }
  </code></pre>