Iterative DFS vs Recursive DFS and different elements order
Here I leave my solution recursively, very fast to implement. It is only a matter of adjusting it for any problem that requires the use of this algorithm.
It is very important to mark the current state as visited, defined as ok[u] = true
, even having all the states as they have not been visited using memset(ok, 0, sizeof ok)
#define forn(i , a , b) for(int i=(a);i<(b);i++)
vector<int> arr[10001];
bool ok[10001];
void addE(int u , int v){
arr[u].push_back(v);
arr[v].push_back(u);
}
void dfs(int u){
ok[u] = true;
forn(v , 0 , (int)arr[u].size()) if(!ok[arr[u][v]]) dfs(arr[u][v]);
}
int main(){
//...
memset(ok , 0 , sizeof ok);
//...
return 0;
}
The most obvious diff is the order you utilize the children.
In the Recursive method: You take the first child and run with it as soon as it comes
while in iterative approach: You push all the children in the stack and then take the top of the stack i.e the last child
To produce the same result just do the insertion of children in reverse order.
The other diff would be memory usage as one would use call stack while the other would use a stack that you make or one the STL elements:
You can read about this here: https://codeforces.com/blog/entry/17307
Both are valid DFS algorithms. A DFS does not specify which node you see first. It is not important because the order between edges is not defined [remember: edges are a set usually]. The difference is due to the way you handle each node's children.
In the iterative approach: You first insert all the elements into the stack - and then handle the head of the stack [which is the last node inserted] - thus the first node you handle is the last child.
In the recursive approach: You handle each node when you see it. Thus the first node you handle is the first child.
To make the iterative DFS yield the same result as the recursive one - you need to add elements to the stack in reverse order [for each node, insert its last child first and its first child last]