Can someone tell me how to write a better version of DFS for calculation of start time and finish time (NON-RECURSIVE DFS using STACK)
In this question: Question, we basically had to calculate start time and finish time for DFS run. I tried implementing, but in the end it became too hacky and I just got it to work after some jugaad.
Here is the solution I submit: submission
The relevant portion of DFS is given below:
// dfs to get intime and outtime
fill(vis.begin(), vis.end(), 0);
vector<LL> in_time(n, -1);
vector<LL> out_time(n);
stack<LL> st;
st.push(0);
LL t = 0;
vis[0] = 1;
while (!st.empty()) {
LL u = st.top();
if (in_time[u] == -1) {
in_time[u] = t; t++;
}
LL cnt = 0;
for (auto v : adj[u]) {
if (!vis[v]) {
vis[v] = 1;
st.push(v);
cnt++;
}
}
if (!cnt) {
out_time[u] = t; t++;
st.pop();
}
}
I just need to write a better version of this NONRECURSIVE DFS using stack to calculate in, out time
Any advice is well recieved.