fork download
  1. #include<iostream>
  2. #include<vector>
  3. #include<stack>
  4.  
  5. using namespace std;
  6.  
  7. // Function to perform Depth-First Search
  8. void DFS(vector<vector<int>>& graph, int start, vector<bool>& visited) {
  9. // Stack to keep track of nodes to visit
  10. stack<int> stack;
  11.  
  12. // Push the starting node onto the stack
  13. stack.push(start);
  14.  
  15. // Mark the starting node as visited
  16. visited[start] = true;
  17.  
  18. // Iterate until the stack is empty
  19. while (!stack.empty()) {
  20. // Get the top node from the stack
  21. int current = stack.top();
  22. stack.pop();
  23. cout << current << " "; // Process the current node
  24.  
  25. // Visit all adjacent nodes
  26. for (int neighbor : graph[current]) {
  27. // If the neighbor has not been visited, mark it as visited and push it onto the stack
  28. if (!visited[neighbor]) {
  29. visited[neighbor] = true;
  30. stack.push(neighbor);
  31. }
  32. }
  33. }
  34. }
  35.  
  36. int main() {
  37. // Sample graph represented as an adjacency list
  38. vector<vector<int>> graph = {
  39. {1, 2}, // Node 0 is connected to nodes 1 and 2
  40. {0, 3, 4}, // Node 1 is connected to nodes 0, 3, and 4
  41. {0, 5}, // Node 2 is connected to nodes 0 and 5
  42. {1}, // Node 3 is connected to node 1
  43. {1}, // Node 4 is connected to node 1
  44. {2} // Node 5 is connected to node 2
  45. };
  46.  
  47. // Number of nodes in the graph
  48. int numNodes = graph.size();
  49.  
  50. // Vector to keep track of visited nodes
  51. vector<bool> visited(numNodes, false);
  52.  
  53. // Start DFS from node 0
  54. cout << "Depth-First Search starting from node 0: ";
  55. DFS(graph, 0, visited);
  56. cout << endl;
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
Depth-First Search starting from node 0: 0 2 5 1 4 3