fork download
  1. #include <bits/stdc++.h>
  2. #define endl "\n"
  3. using namespace std;
  4.  
  5. void callMyDFSFunction(int** a , int n , int sv , bool* visited) {
  6. visited[sv] = true;
  7. cout << sv << " ";
  8. for(int i=0 ; i<n ; i++) {
  9. if(sv == i){ continue; }
  10. if(a[sv][i] and !visited[i]){ callMyDFSFunction(a,n,i,visited); }
  11. }
  12. }
  13. void DFS(int** a , int n){
  14. bool* visited = new bool[n]{false};
  15. for(int i=0 ; i<n ; i++) {
  16. if(!visited[i]) {
  17. callMyDFSFunction(a,n,i,visited);
  18. }
  19. }
  20. }
  21. int main(int argc, char const *argv[])
  22. {
  23. int n;
  24. cin >> n;//No of nodes
  25. int** a = new int*[n]();
  26. for(int i=0 ; i<n ; i++){ a[i] = new int[n](); }
  27.  
  28. bool* visited = new bool[n]{false};
  29.  
  30. int edges , x , y;
  31. cin >> edges;
  32. for(int i=0 ; i<edges ; i++){
  33. cin >> x >> y;
  34. a[x][y] = 1;
  35. a[y][x] = 1;
  36. }
  37. for(int i=0;i<n;i++){for(int j=0;j<n;j++){cout<<a[i][j]<<" ";}cout<<endl;}
  38. cout << endl;
  39. DFS(a,n);
  40.  
  41. for(int i=0 ; i<n ; i++){ delete[] a[i]; }
  42. delete[] a;
  43. return 0;
  44. }
Runtime error #stdin #stdout #stderr 0s 4392KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length