forked from xharaken/step2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
101 lines (82 loc) · 2.46 KB
/
dfs.py
File metadata and controls
101 lines (82 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#! /usr/bin/python3
import collections
# An example graph structure
links = {"A": ["B","E","G"],
"B": ["C"],
"C": ["D"],
"D": ["E"],
"E": ["B","F"],
"F": [],
"G": ["F"]}
# A helper function to find a path.
def find_path(goal, previous):
path = []
node = goal
path.append(node)
while previous[node]:
node = previous[node]
path.append(node)
path.reverse()
return path
# dfs_with_recursion finds A -> B -> C -> D -> E -> F first.
def dfs_with_recursion(start, goal):
print("dfs_with_recursion:")
visited = {}
previous = {}
visited[start] = True
previous[start] = None
recursion(start, goal, visited, previous)
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
def recursion(node, goal, visited, previous):
if node == goal:
return True
for child in links[node]:
if not child in visited:
visited[child] = True
previous[child] = node
if recursion(child, goal, visited, previous):
return True
return False
# dfs_with_stack finds A -> G -> F first.
def dfs_with_stack(start, goal):
print("dfs_with_stack:")
stack = collections.deque()
visited = {}
previous = {}
stack.append(start)
visited[start] = True
previous[start] = None
while len(stack):
node = stack.pop()
if node == goal:
break
for child in links[node]:
if not child in visited:
stack.append(child)
visited[child] = True
previous[child] = node
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
# Challenge quiz: Implement DFS using a stack that visits nodes and edges
# in the same order as dfs_with_recursion. In other words, implement DFS that
# finds A -> B -> C -> D -> E -> F first using a stack.
def dfs_with_stack_in_the_recursion_order(start, goal):
print("dfs_with_stack_in_the_recursion_order:")
stack = collections.deque()
visited = {}
previous = {}
#------------------------#
# Write your code here! #
#------------------------#
if goal in previous:
print(" -> ".join(find_path(goal, previous)))
else:
print("Not found")
dfs_with_recursion("A", "F")
dfs_with_stack("A", "F")
dfs_with_stack_in_the_recursion_order("A", "F")