fork download
  1. // AUTHOR : SOUMEN SEN
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. vector<int>adj[100];
  5. int visited[100];
  6.  
  7. void revisited(int n) {
  8. for(int i = 1; i<=n; i++) {
  9. visited[i] = 0;
  10. }
  11. }
  12.  
  13. void dfs(int node) {
  14. visited[node] = 1;
  15. for(auto neighbour:adj[node]) {
  16. if(!visited[neighbour]) {
  17. dfs(neighbour);
  18. }
  19. }
  20. cout<<node<<" ";
  21. }
  22.  
  23. void bfs(int node) {
  24. queue<int> q;
  25. visited[node] = 1;
  26. q.push(node);
  27.  
  28. while(!q.empty()) {
  29. int current = q.front();
  30. q.pop();
  31. cout<<current<<" ";
  32.  
  33. for(auto neighbour : adj[current]) {
  34. if(!visited[neighbour]) {
  35. visited[neighbour] = 1;
  36. q.push(neighbour);
  37. }
  38. }
  39. }
  40. }
  41.  
  42. int main() {
  43. freopen("input.txt","r",stdin);
  44. int vertices, edges;
  45. cin>>vertices>>edges;
  46.  
  47. revisited(vertices);
  48.  
  49. for(int i = 0; i<edges; i++) {
  50. int u,w;
  51. cin>>u>>w;
  52. if(u == w) {
  53. adj[u].push_back(w);
  54. }
  55. else {
  56. adj[u].push_back(w);
  57. adj[w].push_back(u);
  58. }
  59. }
  60. cout<<"\n\n--------------------------------- adjacency List -------------------------\n\n";
  61. for(int i = 1; i<=vertices; i++) {
  62. cout<<i<<" : ";
  63. for(auto height : adj[i]) {
  64. cout<<height<<" ";
  65. }
  66. cout<<endl;
  67. }
  68. cout<<"-------------------- Travarsal ----------------------------\n\n";
  69.  
  70. cout<<"---------------------DFS---------------\n";
  71. dfs(1);
  72. cout<<endl;
  73.  
  74. cout<<"---------------------BFS---------------\n";
  75. revisited(vertices);
  76. bfs(1);
  77. cout<<endl;
  78. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout

--------------------------------- adjacency List -------------------------

1 : 
2 : 
-------------------- Travarsal ----------------------------

---------------------DFS---------------
1 
---------------------BFS---------------
1