Skip to content

Instantly share code, notes, and snippets.

@201411108
Last active July 18, 2021 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 201411108/02d4e97a7bf61fac4ec96827054a36f8 to your computer and use it in GitHub Desktop.
Save 201411108/02d4e97a7bf61fac4ec96827054a36f8 to your computer and use it in GitHub Desktop.
DFS(stack)_python
def iterative_dfs(start_v):
discovered = []
stack = [start_v]
while stack:
v = stack.pop()
if v not in discovered:
discovered.append(v)
for w in graph[v]:
stack.append(w)
return discovered
# adjacency list graph
graph = {
1: [2, 3, 4],
2: [5],
3: [5],
4: [],
5: [6, 7],
6: [],
7: [3],
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment