I have managed to find shortest path for unweighted graph using recursive dfs. Here is such an attempt.
void dfsHelper(graph*& g, int start,int end, bool*& visited, int& min, int i) {
visited[start] = true;
i = i + 1;
if (start == end) {
if (i<=min) { min = i; }
}
node* current = g->adj[start];
while (current != NULL) {
if (!visited[current->dest]) {
dfsHelper(g, current->dest,end, visited,min,i);
}
current = current->next;
}
visited[start] = false;
}
However for an iterative algorithm of dfs such as this one, how should I approach.
void dfsItr(graph*& g, int start, int end) {
bool* isVisited = new bool[g->numVertex];
for (int i = 0; i < g->numVertex; ++i) {
isVisited[i] = false;
}
stack<int> st;
isVisited[start] = true;
st.push(start);
while (!st.empty()) {
start = st.top();
cout << start << " ";
st.pop();
node* current = g->adj[start];
while (current != NULL) {
if (!isVisited[current->dest]) {
isVisited[current->dest] = true;
st.push(current->dest);
if (current->dest == end) {
cout << current->dest << endl;
}
}
current = current->next;
}
}
}
Is there any algorithm detailing about the procedure to follow. I am well aware of finding shortest path using BFS algorithm as given here or as suggested here. My initial intuition as to why such idea would work for BFS is that the traversal happens layer by layer,multiple children share same parent in each layer, so it is easy to backtrack just by following the parent node. In iterative dfs, it is not the case. Can someone shed some light as to how to proceed. Is there any proven algorithm to tackle this scenario. Thanks.