fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function to add an edge to the adjacency list
  5. void addEdge(vector<int> adj[], int u, int v) {
  6. adj[u].push_back(v); // Add v to u's list
  7. adj[v].push_back(u); // Add u to v's list (for undirected graph)
  8. }
  9.  
  10. // Function to perform DFS using a stack
  11. void DFS(vector<int> adj[], int V, int start) {
  12. vector<bool> visited(V, false); // To keep track of visited nodes
  13. stack<int> st; // Stack for DFS
  14.  
  15. st.push(start); // Push the starting node to the stack
  16.  
  17. cout << "DFS traversal starting from node " << start << ": ";
  18. while (!st.empty()) {
  19. int node = st.top(); // Get the top element
  20. st.pop();
  21.  
  22. // If the node is not visited, process it
  23. if (!visited[node]) {
  24. cout << node << " ";
  25. visited[node] = true;
  26. }
  27.  
  28. // Push all unvisited neighbors to the stack
  29. for (int neighbor : adj[node]) {
  30. if (!visited[neighbor]) {
  31. st.push(neighbor);
  32. }
  33. }
  34. }
  35. cout << endl;
  36. }
  37.  
  38. int main() {
  39. int V = 6; // Number of vertices
  40. vector<int> adj[V]; // Adjacency list
  41.  
  42. // Adding edges
  43. addEdge(adj, 0, 1);
  44. addEdge(adj, 0, 2);
  45. addEdge(adj, 1, 3);
  46. addEdge(adj, 1, 4);
  47. addEdge(adj, 2, 4);
  48. addEdge(adj, 3, 5);
  49. addEdge(adj, 4, 5);
  50.  
  51. // Perform DFS starting from node 0
  52. DFS(adj, V, 0);
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
DFS traversal starting from node 0: 0 2 4 5 3 1