-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.py
More file actions
98 lines (77 loc) · 2.69 KB
/
main.py
File metadata and controls
98 lines (77 loc) · 2.69 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
import argparse
import time
from board import Board
from input import get_start_board
def bfs(init_board):
"""BFS searching algorithm
Args:
init_board: initial board/state
Returns:
curr_state: one possible final state
steps: total moving steps
"""
queue = []
visited = set()
steps = 0
queue.append(init_board)
visited.add(init_board.string)
start = time.time()
while queue:
size = len(queue)
print(f"Step: {steps}, #States total: {len(queue)}")
for _ in range(size):
curr_state = queue.pop(0)
if curr_state.state_checking() is True:
print('Elapsed time: {:.4f}s'.format(time.time() - start))
return curr_state, steps
for state in curr_state.next_boards():
state_str = state.string
if state_str not in visited:
queue.append(state)
visited.add(state_str)
steps += 1
def dfs(init_board):
"""DFS searching algorithm
Args:
init_board: initial board/state
Returns:
curr_state: one possible final state
"""
stack = []
stack.append(init_board)
visited = set()
start = time.time()
while stack:
curr_state = stack.pop()
if curr_state.state_checking() is True:
print('Elapsed time: {:.4f}s'.format(time.time() - start))
return curr_state
if curr_state.string not in visited:
visited.add(curr_state.string)
for next_state in curr_state.next_boards():
stack.append(next_state)
if __name__ == '__main__':
# 1. prepare args parser
parser = argparse.ArgumentParser('Choose searching method')
parser.add_argument('--search', type=str, default='dfs')
args = parser.parse_args()
# 2. get initital game board
start_board = Board(get_start_board(), parent=None)
# 3. run searching algorithm
if args.search == 'bfs':
final_state, total_steps = bfs(init_board=start_board)
elif args.search == 'dfs':
final_state = dfs(init_board=start_board)
else:
raise ValueError('Unvalid searching algorithm, please check it again.')
print('final state string: {}'.format(final_state.string))
# 4. get actions
total_actions = []
total_strings = []
while final_state:
total_strings.append(final_state.string)
action = f"Move {final_state.from_which + 1} to {final_state.to_which + 1}"
total_actions.append(action)
final_state = final_state.parent
for idx, data in enumerate(zip(total_strings[::-1], total_actions[::-1])):
print(f"Step: {idx}, Action: {data[1]}")