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.
2
6
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)
3
13
"""
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
- """
11
14
15
+ from typing import Set , Dict
16
+
17
+
18
+ def dfs (graph : Dict , start : str ) -> Set [int ]:
19
+ """Depth First Search on Graph
12
20
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
+ """
18
25
explored , stack = set (start ), [start ]
19
26
while stack :
20
27
v = (
21
28
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
23
31
for w in graph [v ]:
24
32
if w not in explored :
25
33
explored .add (w )
@@ -36,4 +44,5 @@ def dfs(graph, start):
36
44
"F" : ["C" , "E" ],
37
45
}
38
46
39
- print (dfs (G , "A" ))
47
+ if __name__ == "__main__" :
48
+ print (dfs (G , "A" ))
0 commit comments