Skip to content

Commit de64f33

Browse files
authored
Add type hints, rearrange doc-strings and comments
1 parent 3a7b2d2 commit de64f33

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

graphs/dfs.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
1-
"""pseudo-code"""
1+
"""The DFS function simply calls itself recursively for every unvisited child of
2+
its argument. We can emulate that behaviour precisely using a stack of iterators.
3+
Instead of recursively calling with a node, we'll push an iterator to the node's
4+
children onto the iterator stack. When the iterator at the top of the stack
5+
terminates, we'll pop it off the stack.
26
7+
Pseudocode:
8+
all nodes initially unexplored
9+
mark s as explored
10+
for every edge (s, v):
11+
if v unexplored:
12+
DFS(G, v)
313
"""
4-
DFS(graph G, start vertex s):
5-
// all nodes initially unexplored
6-
mark s as explored
7-
for every edge (s, v):
8-
if v unexplored:
9-
DFS(G, v)
10-
"""
1114

15+
from typing import Set, Dict
16+
17+
18+
def dfs(graph: Dict, start: str) -> Set[int]:
19+
"""Depth First Search on Graph
1220
13-
def dfs(graph, start):
14-
"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate that
15-
behaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iterator
16-
to the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll pop
17-
it off the stack."""
21+
:param graph: directed graph in dictionary format
22+
:param vertex: starting vectex as a string
23+
:returns: the trace of the search
24+
"""
1825
explored, stack = set(start), [start]
1926
while stack:
2027
v = (
2128
stack.pop()
22-
) # one difference from BFS is to pop last element here instead of first one
29+
)
30+
# one difference from BFS is to pop last element here instead of first one
2331
for w in graph[v]:
2432
if w not in explored:
2533
explored.add(w)
@@ -36,4 +44,5 @@ def dfs(graph, start):
3644
"F": ["C", "E"],
3745
}
3846

39-
print(dfs(G, "A"))
47+
if __name__ == "__main__":
48+
print(dfs(G, "A"))

0 commit comments

Comments
 (0)