dfs Posted on 2019-08-02 | In algorithm | Comments: 123456struct GraphNode { int val; vector<GraphNode *> neighbors;};unordered_set<GraphNode *> visited; Recursive DFS 123456789void dfs(GraphNode &nd) { printf("%d", nd.val); visited.insert(&nd); for (auto next : nd.neighbors) if (!visited.count(next)) { dfs(*next); }} Non-recursive DFS 1234567891011121314151617void no_recursive_dfs(GraphNode &start) { stack<GraphNode *> s; s.push(&start); while (!s.empty()) { auto cur = s.top(); s.pop(); printf("%d\n", cur->val); for (auto next : cur->neighbors) { if (!visited.count(next)) { s.push(next); visited.insert(next); } } }}