Skip to content

Initialize set with source in DFS #1872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Apr 17, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 26 additions & 24 deletions graphs/dfs.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
"""pseudo-code"""

"""
DFS(graph G, start vertex s):
// all nodes initially unexplored
mark s as explored
for every edge (s, v):
if v unexplored:
DFS(G, v)
"""The DFS function simply calls itself recursively for every unvisited child of
its argument. We can emulate that behaviour precisely using a stack of iterators.
Instead of recursively calling with a node, we'll push an iterator to the node's
children onto the iterator stack. When the iterator at the top of the stack
terminates, we'll pop it off the stack.

Pseudocode:
all nodes initially unexplored
mark s as explored
for every edge (s, v):
if v unexplored:
DFS(G, v)
"""

from typing import Set, Dict

def dfs(graph, start):
"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that
behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator
to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop
it off the stack."""
explored, stack = set(), [start]
while stack:
v = (
stack.pop()
) # one difference from BFS is to pop last element here instead of first one

if v in explored:
continue

explored.add(v)
def dfs(graph: Dict, start: str) -> Set[int]:
"""Depth First Search on Graph

:param graph: directed graph in dictionary format
:param vertex: starting vectex as a string
:returns: the trace of the search
"""
explored, stack = set(start), [start]
while stack:
v = stack.pop()
# one difference from BFS is to pop last element here instead of first one
for w in graph[v]:
if w not in explored:
explored.add(w)
stack.append(w)
return explored

Expand All @@ -41,4 +42,5 @@ def dfs(graph, start):
"F": ["C", "E"],
}

print(dfs(G, "A"))
if __name__ == "__main__":
print(dfs(G, "A"))