Advertisement
illeas

DFS

Aug 2nd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. bool visited[1000];
  5. int graph[100][100], nodes, edges;
  6.  
  7. void dfs(int source, int destination)
  8. {
  9. stack<int> s;
  10.  
  11. s.push(source);
  12. visited[source] = true;
  13.  
  14. printf("\n\nTraversing from source to destination: ");
  15. while (!s.empty())
  16. {
  17.  
  18. int t = s.top();
  19. printf("%d ",t);
  20. s.pop();
  21.  
  22. // End loop if destination is traversed
  23. if(t == destination)
  24. {
  25. printf("\n");
  26. break;
  27. }
  28.  
  29. // Check all the nodes to see if it is connected with f
  30. for(int i=1; i<=nodes; i++)
  31. {
  32. // If f and i are connected and i is not visited then push i and make it visited
  33. if(graph[t][i] == 1 && visited[i] == false)
  34. {
  35. s.push(i);
  36. visited[i] = true;
  37. }
  38. }
  39. }
  40. }
  41. int main()
  42. {
  43. printf("Input number of Nodes and Edges: ");
  44. scanf("%d %d",&nodes,&edges);
  45.  
  46. int a, b, source, destination;
  47. printf("\nInput the edges: \n");
  48.  
  49. for (int i = 1; i <= edges; i++)
  50. {
  51. scanf("%d %d",&a,&b);
  52.  
  53. // Making an undirected graph. if graph[a][b] has value of 1 means a and b are connected
  54. graph[a][b] = 1;
  55. graph[b][a] = 1; // If a and b is connected then we also need to connect b and a
  56. }
  57.  
  58. printf("\n\nInput source: ");
  59. scanf("%d",&source);
  60.  
  61. printf("\n\nInput destination: ");
  62. scanf("%d",&destination);
  63.  
  64. // Send source and destination to the function
  65. dfs(source, destination);
  66.  
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement