I have the below code for depth first search:
def dfs(graph, vertex):
visited = set()
stack = [vertex]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
stack.extend(graph[vertex])
return visited
def main():
test_graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
print(dfs(test_graph, 'A'))
if __name__ == '__main__':
main()
On every execution I'm getting a different output.
Is there any change I can make such that the output always starts with the value of vertex (in this case A)?