I'm trying to implement DFS, however, according to A StackOverFlow link about DFS, a DFS uses only Stack.
This is my current implementation:
def DFS_graph_recursive(graph, start, end, stack):
#Stack to push the node when we are entering the node
stack.append(start)
while(end not in stack):
for i in graph.edges[start]:
#check if this is inside the stack, to make sure that it doesn't try to go back
if (i not in stack):
#Recursive Call
DFS_graph_recursive(graph, i, end, stack)
#Pop the stack when we are leaving this node, but need to make sure if end is inside
if(end not in stack):
stack.pop()
There is a few issues, the time complexity does not look like O(|E|). The first while loop is O(|E|), however, I need to check whether if my next node is already inside the stack, to avoid going backwards, if this stack is large, and I assume that i not in stack
takes O(n) to compute, making this algorithm look like O(|E|^2) in complexity.
The if(end not in stack)
, makes the algorithm worse in terms of time complexity, since for each edge search, it needs to check if end is in the stack, meaning we don't want to pop the stack if we found a solution. This furthermore increases time complexity to O(|E|^2 + |E|). Is there a way to do this with only one while loop?
In terms of space complexity, it should be O(|V|) worst case that we have a long tree with a branching factor of 1.
I can easily implement a O(|E|) solution if it was a binary tree type, that has a directed path going down to children nodes. The issue is that since the problem is a undirected graph, let's say there are two vertexes, A and B. If A connect to B, then B connect to A. So if I don't check if (i not in stack)
I will be stuck going back and forth from A to B, B to A... etc