fork download
  1. #include <iostream>
  2. #include <unordered_set>
  3. #include <unordered_map>
  4. #include <vector>
  5. using namespace std;
  6.  
  7. struct Node {
  8. int val;
  9. unordered_map<Node*, int> edges;
  10. Node(int val): val(val) {}
  11. void addEdge(Node* node, int weight = 1) {
  12. edges[node] = weight;
  13. }
  14. };
  15.  
  16. void dfs_helper(Node* node, unordered_set<Node*> &visiting, unordered_set<Node*> &visited){
  17. if(!node || visiting.find(node)!=visiting.end()) return;
  18. if(visited.find(node)!=visited.end()){
  19. cout<<"Not exploring again: "<<node->val<<endl;
  20. return;
  21. }
  22. visited.insert(node);
  23. visiting.insert(node);
  24. cout<<"Visiting: "<<node->val<<endl;
  25. for(auto p: node->edges){
  26. dfs_helper(p.first, visiting, visited);
  27. }
  28. cout<<"Leaving: "<<node->val<<endl;
  29. visiting.erase(node);
  30. }
  31.  
  32. void dfs(Node* root){
  33. unordered_set<Node*> visiting;
  34. unordered_set<Node*> visited;
  35. dfs_helper(root, visiting, visited);
  36. return;
  37. }
  38.  
  39. unordered_map<int, Node*> generate_graph(vector<pair<int,int>> &edges){
  40. unordered_map<int, Node*> graph;
  41. int i,j;
  42. for(auto p: edges){
  43. i = p.first;
  44. j = p.second;
  45. if(graph.find(i)==graph.end()) graph[i] = new Node(i);
  46. if(graph.find(j)==graph.end()) graph[j] = new Node(j);
  47. graph[i]->addEdge(graph[j]);
  48. graph[j]->addEdge(graph[i]);
  49. }
  50. return graph;
  51. }
  52. int main() {
  53. int t;
  54. int a, b;
  55. cin>>t;
  56. vector<pair<int,int>> v;
  57. while(t--){
  58. cin>>a>>b;
  59. v.push_back({a,b});
  60. }
  61. unordered_map<int, Node*> graph = generate_graph(v);
  62. dfs(graph.begin()->second);
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5280KB
stdin
30
0 4
0 5
0 10
0 13
1 16
2 3
2 14
2 17
3 5
3 12
3 17
3 18
4 7
5 6
5 10
5 11
5 14
5 15
6 8
7 19
9 17
10 16
10 17
10 18
11 14
11 19
13 16
14 15
15 16
15 18
stdout
Visiting: 9
Visiting: 17
Visiting: 10
Visiting: 18
Visiting: 15
Visiting: 16
Visiting: 13
Visiting: 0
Visiting: 4
Visiting: 7
Visiting: 19
Visiting: 11
Visiting: 5
Visiting: 3
Visiting: 12
Leaving: 12
Visiting: 2
Visiting: 14
Leaving: 14
Leaving: 2
Leaving: 3
Visiting: 6
Visiting: 8
Leaving: 8
Leaving: 6
Not exploring again: 14
Leaving: 5
Not exploring again: 14
Leaving: 11
Leaving: 19
Leaving: 7
Leaving: 4
Not exploring again: 5
Leaving: 0
Leaving: 13
Visiting: 1
Leaving: 1
Leaving: 16
Not exploring again: 5
Not exploring again: 14
Leaving: 15
Not exploring again: 3
Leaving: 18
Not exploring again: 16
Not exploring again: 0
Not exploring again: 5
Leaving: 10
Not exploring again: 2
Not exploring again: 3
Leaving: 17
Leaving: 9