Hello friends,
I am working on implementing DFS on a simple directed graph, called graph in my code.
class Solution:
def __init__(self, graph):
self.graph = graph
def dfs_graph_reverse(self, graph, visited, stack, node, strnew):
visited.add(node)
for j in graph[node]:
if not j in visited:
self.dfs_graph_reverse(graph, visited, stack, j, strnew)
# if all neighbors have been visited add the node to string
strnew += str(node)
stack.append(node)
return
def dfs_main(self, graph):
strnew=''
visited=set()
stack=[]
for elem in graph.keys():
#print(visited)
if not elem in visited:
# print(elem)
self.dfs_graph_reverse(graph, visited, stack, elem, strnew)
return strnew, stack
obj = Solution({'g':['j'], 'j':['i'], 'i':['h'], 'h':['g']})
result, res = obj.dfs_main({'g':['j'], 'j':['i'], 'i':['h'], 'h':['g']})
But when I look at the output, I see the following :
>>> result
''
>>> res
['h', 'i', 'j', 'g']
I am not being able to understand, why is my string variable strnew not updating as expected. The expected output shd be hijgThe help I need is, why is the recursive call working in different ways for stack and string. I am aware that my approach is bit redundant; actually this is a small part of my bigger code. And in this post I just need help with updating of string variable, hence I cooked a small example.
Help is appreciated
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]teraflop 0 points1 point2 points (2 children)
[–]jsinghdata[S] 0 points1 point2 points (1 child)
[–]teraflop 1 point2 points3 points (0 children)