Saturday 23 June 2018

Depth First Search DFS (code (C++)

This algorithm can transverse a graph and find all the reachable points


 1  #include<bits/stdc++.h>
 2  using namespace std;
 3  int n,e;
 4  vector<int>g[128];
 5  bool seen[128];
 6 
 7  void dfs(int u){
 8  seen[u] = true;
 9  cout<<u<<" ";
10  for(int i=0;i<g[u].size();i++){
11      int v = g[u][i];
12      if(!seen[v])dfs(v);
13  printf("\n");
14  }
15 
16  }
17  int main(){
18  cin>>n>>e;
19  for(int i=0;i<n;i++){
20      int u,v;
21      cin>>u>>v;
22      g[u].push_back(v);
23  }
24  for(int i = 1;i<=n;i++ ){
25      if(!seen[i]){
26          dfs(i);
27      }
28  }
29 
30  return 0;}

Spoj Problem ACMCEG2C - Pick the candies (C++)

  The problem link may be found here.       Explanation: Use Deque to keep track of elements of the variety of candies. If i is gre...