1. Iterative DFS Using Explicit Stack
Intuition
Push vertex 0 onto a stack. While the stack is non-empty, pop the top node. If not visited, mark it visited, add to result, and push all its neighbors in reverse order (to maintain left-to-right exploration).
Algorithm
- Initialize visited array of size V to false.
- Push source vertex 0 onto stack.
- While stack is not empty:
- Pop vertex u from stack.
- If visited[u], continue.
- Mark visited[u] = true and append u to result.
- Iterate neighbors of u in reverse order and push unvisited neighbors onto stack.
- Return result.
#include <iostream>#include <vector>#include <stack> class Solution {public: std::vector<int> dfsOfGraph(int V, std::vector<std::vector<int>>& adj) { std::vector<bool> visited(V, false); std::vector<int> result; std::stack<int> st; st.push(0); while (!st.empty()) { int u = st.top(); st.pop(); if (visited[u]) continue; visited[u] = true; result.push_back(u); for (int i = (int)adj[u].size() - 1; i >= 0; --i) { int v = adj[u][i]; if (!visited[v]) { st.push(v); } } } return result; }}; int main() { Solution sol; std::vector<std::vector<int>> adj = {{2, 3, 1}, {0}, {0, 4}, {0}, {2}}; std::vector<int> res = sol.dfsOfGraph(5, adj); std::cout << "Iterative DFS: "; for (int x : res) std::cout << x << " "; std::cout << "\nExpected: 0 2 4 3 1\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)