forked from xmojtabw/AI-Tetris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
76 lines (62 loc) · 1.91 KB
/
bfs.py
File metadata and controls
76 lines (62 loc) · 1.91 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
from queue import Queue , LifoQueue
class Node:
def __init__(self, data, action=None, parent: "Node | None" = None, depth=0):
self.state = data
self.action = action
self.parent = parent
self.depth = depth
def expand(problem, node: Node):
for action in problem.actions:
child = problem.result(node, action)
if child: # if child is not none
yield child
def BFS(problem):
node = Node(data=problem.initial)
if problem.is_goal(node.state):
return node
frontier = Queue()
frontier.put(node)
reached = {problem.initial}
while not frontier.empty():
node = frontier.get()
for child in expand(problem, node):
s = child.state
if problem.is_goal(s):
return child
if s not in reached:
reached.add(s)
frontier.put(child)
return None
def is_cycle(node: Node) -> bool:
current = node #compare the node with all of it's parent
while current.parent is not None:
if current.parent.state == node.state:
return True
current = current.parent
return False
def DLS(problem, limit=7):
node = Node(problem.initial)
frontier = LifoQueue()
frontier.put(node)
result = None
while not frontier.empty():
node = frontier.get()
if problem.is_goal(node.state):
return node
if node.depth >= limit:
result = "cut-off"
elif not is_cycle(node):
for child in expand(node=node, problem=problem):
frontier.put(child)
return result
def trace_back(node: Node) -> list:
answers = []
child = None
while node:
if child:
answers.append([node.state, child.action])
else:
answers.append([node.state, "answer"])
child = node
node = node.parent
return answers[::-1]