-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs.py
More file actions
50 lines (35 loc) · 1.36 KB
/
Copy pathdfs.py
File metadata and controls
50 lines (35 loc) · 1.36 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
'''Depth-first Search'''
class Node:
def __init__(self, state, parent, depth):
self.state = state
self.parent = parent
self.depth = depth
def expand(graph, node):
children = graph.get(node.state, [])
children_nodes = []
for child in children:
child_node = Node(child, node, node.depth+1)
children_nodes.append(child_node)
return children_nodes
def goal_path(node):
path = []
while node:
path.append(node.state)
node = node.parent
return path[::-1]
def DFS(graph, start, goal):
stack = [] # LIFO frontier queue: push = append() , pop = pop()
visited = set() # Prevent redundant exploration
stack.append(Node(start, None, 0))
visited.add(start)
while stack:
node = stack.pop()
if node.state == goal: # Goal test at expansion time
return goal_path(node)
children = expand(graph, node)
children.reverse()
for child in children:
if child.state not in visited:
visited.add(child.state) # Mark as visisted when the node generates
stack.append(child)
return 'Failure'