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.  
  63. cout<<"\t"<<i<<": ";
  64. for(auto height : adj[i]) {
  65. cout<<height<<" ";
  66. }
  67. cout<<endl;
  68. }
  69. cout<<"-------------------- Travarsal ----------------------------\n\n";
  70.  
  71. cout<<"---------------------DFS---------------\n";
  72. cout<<"\t";
  73. dfs(1);
  74. cout<<endl;
  75. cout<<endl;
  76.  
  77. cout<<"---------------------BFS---------------\n";
  78. revisited(vertices);
  79. cout<<"\t";
  80. bfs(1);
  81. cout<<endl;
  82. cout<<endl;
  83. }
Success #stdin #stdout 0s 5312KB
stdin
Standard input is empty
stdout

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

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

---------------------DFS---------------
	1 

---------------------BFS---------------
	1