fork download
  1. //
  2. // main.cpp
  3. // DFS in Graph
  4. //
  5. // Created by Himanshu on 27/08/21.
  6. //
  7.  
  8. #include <iostream>
  9. #include <vector>
  10. using namespace std;
  11.  
  12. //n = number of nodes in graph
  13. void DFS (int x, int n, vector<int> graph[], int vis[]) {
  14. vis[x] = 1;
  15. cout<<x<<" ";
  16. for (int i=0; i<graph[x].size(); i++) {
  17. int j = graph[x][i];
  18. if (vis[j] == 0) {
  19. DFS(j, n, graph, vis);
  20. }
  21. }
  22. }
  23.  
  24.  
  25. int main() {
  26. int s = 1, n = 6;
  27. vector<int> graph[n+1];
  28. int vis[n+1];
  29.  
  30. graph[1].push_back(2);
  31. graph[2].push_back(1);
  32. graph[2].push_back(4);
  33. graph[3].push_back(5);
  34. graph[4].push_back(2);
  35. graph[4].push_back(5);
  36. graph[4].push_back(6);
  37. graph[5].push_back(3);
  38. graph[5].push_back(4);
  39. graph[6].push_back(4);
  40.  
  41.  
  42. for (int i=1; i<=n; i++) {
  43. vis[i] = 0;
  44. }
  45.  
  46. cout<<"Graph:"<<endl;
  47. for (int i=1; i<=n; i++) {
  48. cout<<i<<": ";
  49. for (int j=0; j<graph[i].size(); j++) {
  50. cout<<graph[i][j]<<" ";
  51. }
  52. cout<<endl;
  53. }
  54.  
  55. cout<<endl<<"DFS:"<<endl;
  56. DFS(s, n, graph, vis);
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 5556KB
stdin
Standard input is empty
stdout
Graph:
1: 2 
2: 1 4 
3: 5 
4: 2 5 6 
5: 3 4 
6: 4 

DFS:
1 2 4 5 3 6