-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve_puzzle.py
124 lines (87 loc) · 2.35 KB
/
solve_puzzle.py
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import queue
def find_index(puzzle, item):
row = -1
column = -1
for z in puzzle:
try:
column = list(z).index(item)
row = puzzle.index(z)
except ValueError:
pass
return row, column
def solve_puzzle(puzzle):
print(puzzle)
p = list(puzzle).copy()
if check_answer(p):
print("Solved!")
return p
possible_ways = queue.Queue()
parent = ""
while not check_answer(p):
p = solve(p, possible_ways, parent)
def check_answer(puzzle):
answer = [
["", 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]
]
if puzzle == answer:
return True
else:
return False
def get_available_ways(puzzle):
hole_row, hole_column = find_index(puzzle, "")
if hole_column == 0 and hole_row == 0:
return ['R', 'D']
elif hole_column == 3 and hole_row == 0:
return ['L', 'D']
elif hole_column == 0 and hole_row == 3:
return ['R', 'U']
elif hole_column == 3 and hole_row == 3:
return ['L', 'U']
elif hole_row == 0:
return ['R', 'L', 'D']
elif hole_row == 3:
return ['R', 'L', 'U']
elif hole_column == 0:
return ['R', 'U', 'D']
elif hole_column == 3:
return ['L', 'U', 'D']
else:
return ['R', 'L', 'U', 'D']
def move(puzzle, select, row, col):
if select == 'R':
r2 = row
c2 = col + 1
temp = puzzle[row][col]
puzzle[row][col] = puzzle[r2][c2]
puzzle[r2][c2] = temp
elif select == 'L':
r2 = row
c2 = col - 1
temp = puzzle[row][col]
puzzle[row][col] = puzzle[r2][c2]
puzzle[r2][c2] = temp
elif select == 'U':
r2 = row - 1
c2 = col
temp = puzzle[row][col]
puzzle[row][col] = puzzle[r2][c2]
puzzle[r2][c2] = temp
elif select == 'D':
r2 = row + 1
c2 = col
temp = puzzle[row][col]
puzzle[row][col] = puzzle[r2][c2]
puzzle[r2][c2] = temp
return puzzle
def solve(p, possible_ways, parent):
for w in get_available_ways(p):
possible_ways.put(parent + w)
select = possible_ways.get()
print("Select: ", select)
row, column = find_index(p, "")
p = move(p, select, row, column)
print("P: ", p)
return p