fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. void DFS(int start, vector<int> G[], vector<int>& visited) {
  6. stack<int> stk;
  7. stk.push(start); // Start DFS from this node
  8.  
  9. while (!stk.empty()) {
  10. int node = stk.top();
  11. stk.pop();
  12.  
  13. if (!visited[node]) {
  14. // If node hasn't been visited, process it
  15. cout << node << "\n"; // Visit the node (printing here)
  16. visited[node] = 1; // Mark it as visited
  17.  
  18. // Push all unvisited neighbors of the current node onto the stack
  19. for (auto u : G[node]) {
  20. if (!visited[u]) {
  21. stk.push(u);
  22. }
  23. }
  24. }
  25. }
  26. }
  27. int main() {
  28. int n, m;
  29. cin >> n >> m; // n = number of nodes, m = number of edges
  30. vector<int> G[n+1]; // Graph adjacency list (1-based indexing)
  31.  
  32. for (int i = 0; i < m; i++) {
  33. int u, v;
  34. cin >> u >> v;
  35. G[u].push_back(v); // Add edge u -> v
  36. G[v].push_back(u); // Add edge v -> u (since it's undirected)
  37. }
  38.  
  39. vector<int> visited(n+1, 0); // Visited array to track visited nodes
  40. DFS(1, G, visited); // Start DFS from node 1
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0.01s 5268KB
stdin
8 7 
1 2
1 3
2 4 
2 5 
3 6 
3 7 
5 8
stdout
1
3
7
6
2
5
8
4