fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Graph {
  5. int n, m;
  6. vector<int> head, next;
  7. vector<int> src, dst;
  8. Graph(int n) : n(n), m(0), head(n,-1) { }
  9. int addEdge(int u, int v) {
  10. next.push_back(head[u]);
  11. src.push_back(u);
  12. dst.push_back(v);
  13. return head[u] = m++;
  14. }
  15. };
  16. void dfs(Graph g) {
  17. vector<int> visited(g.n);
  18. function<void(int)> rec = [&](int u) {
  19. cout << u << endl;
  20. visited[u] = true;
  21. int e = g.head[u];
  22. while (e >= 0) {
  23. if (!visited[g.dst[e]]) rec(g.dst[e]);
  24. e = g.next[e];
  25. }
  26. };
  27. rec(0);
  28. }
  29.  
  30. int main() {
  31. Graph g(3);
  32. g.addEdge(0,1);
  33. g.addEdge(1,2);
  34. g.addEdge(2,0);
  35. dfs(g);
  36. }
  37.  
Success #stdin #stdout 0s 4492KB
stdin
Standard input is empty
stdout
0
1
2