fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int graph[1001][1001];
  4. int visit[1001];
  5. int n, e;
  6.  
  7. void DFS(int start)
  8. {
  9. //Using Stack
  10. //Initial Steps
  11. visit[start] = 1;
  12. stack<int>STK;
  13. STK.push(start);
  14. cout<<start<<" ";
  15.  
  16. //Repeating step
  17.  
  18. while(!STK.empty())
  19. {
  20. for(int j = 1; j <= n; j++)
  21. {
  22. int x = STK.top();
  23. if(visit[j] == 0 && graph[x][j] != 0)
  24. {
  25. visit[j] = 1;
  26. STK.push(j);
  27. cout<<j<<" ";
  28. j = 1;
  29. }
  30. }
  31. STK.pop();
  32. }
  33. }
  34.  
  35.  
  36. void DFS_RC(int start)
  37. {
  38. visit[start] = 1;
  39. cout<<start<<" ";
  40.  
  41. for(int j = 1; j <= n; j++)
  42. {
  43. if(visit[j] == 0 && graph[start][j] != 0)
  44. {
  45. visit[j] = 1;
  46. DFS_RC(j);
  47. }
  48. }
  49. }
  50.  
  51.  
  52.  
  53. int main()
  54. {
  55. cin>>n>>e;
  56. int u, v;
  57. for(int i = 1; i <= e; i++)
  58. {
  59. cin>>u>>v;
  60. graph[u][v] = 1;
  61. graph[v][u] = 1;
  62. }
  63. //DFS(1);
  64. DFS_RC(1);
  65.  
  66.  
  67. }
  68.  
Success #stdin #stdout 0.01s 5252KB
stdin
10 13
1 2
2 3
3 4
3 10
3 9
2 5
2 7
2 8
5 6
5 7
5 8
7 8
4 1
stdout
1 2 3 4 9 10 5 6 7 8