fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct node{
  5. int data;
  6. node* next;
  7. node(){
  8. data = 0;
  9. next = NULL;
  10. }
  11. node(int GivenData){
  12. data = GivenData;
  13. next = NULL;
  14. }
  15. };
  16.  
  17. struct LinkedList{
  18. node* head;
  19. LinkedList(){
  20. head = NULL;
  21. }
  22. void push_back(int data){
  23. node* new_node = new node(data);
  24. if (head == NULL) {
  25. head = new_node;
  26. return;
  27. }
  28. node* temp = head;
  29. while(temp->next != NULL) {
  30. temp = temp->next;
  31. }
  32. temp->next = new_node;
  33. }
  34. void print(){
  35. node* temp = head;
  36. while(temp != NULL){
  37. cout << temp->data << " ";
  38. temp = temp->next;
  39. }
  40. cout << endl;
  41. }
  42. };
  43. const int N = 100;
  44. LinkedList adj[N];
  45. vector<int>vis(N);
  46.  
  47. void dfs(int now){
  48. vis[now] = 1;
  49. node* tmp = adj[now].head;
  50. cout << now << " ";
  51. while(tmp != NULL){
  52. if(vis[tmp->data] == 0) dfs(tmp->data);
  53. tmp = tmp->next;
  54. }
  55. }
  56.  
  57. int main(){
  58. int n; cin >> n;
  59. int m; cin >> m;
  60. for(int i = 0; i < m; i++){
  61. int a,b;
  62. cin >> a >> b;
  63. adj[a].push_back(b);
  64. adj[b].push_back(a);
  65. }
  66. cout << "DFS Traversal of the given graph is: ";
  67. dfs(1);
  68. cout << endl;
  69. }
  70.  
Success #stdin #stdout 0.01s 5408KB
stdin
6 5
1 2
2 3
1 4
3 5
2 6
stdout
DFS Traversal of the given graph is: 1 2 3 5 6 4