-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathFinding_7x7.py
More file actions
233 lines (214 loc) · 7.18 KB
/
pathFinding_7x7.py
File metadata and controls
233 lines (214 loc) · 7.18 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
try:
import Queue
except ImportError:
import queue as Queue
import math
### Part 1: define search state
class PathFindingState:
"""
0 = blank
1 = obstacle
2 = start point
3 = goal point
----------------
| 0 0 0 0 0 0 0|
| 0 0 0 0 0 0 0|
| 0 2 0 0 1 0 0|
| 0 0 0 0 0 0 0|
| 0 1 0 0 1 0 0|
| 0 0 0 0 1 3 0|
| 0 0 0 0 0 0 0|
----------------
"""
def __init__(self, numberList):
self.cells = []
self.cells = numberList[:]
self.cellsize = int(math.sqrt(len(self.cells)))
for index in range( self.cellsize*self.cellsize ):
if self.cells[index] == 2:
self.currentLocation = index
if self.cells[index] == 3:
self.goalLocation = index
def goalState(self):
if self.currentLocation == self.goalLocation:
return True
return False
def nextActions(self):
actions = []
index = self.currentLocation
if (index>=self.cellsize) and (self.cells[index-self.cellsize]!=1):
actions.append('up')
if (index<(self.cellsize*(self.cellsize-1))) and (self.cells[index+self.cellsize]!=1):
actions.append('down')
if ((index%self.cellsize)!=0) and (self.cells[index-1]!=1):
actions.append('left')
if ((index%self.cellsize)!=(self.cellsize-1)) and (self.cells[index+1]!=1):
actions.append('right')
return actions
def nextState(self, action):
index = self.currentLocation
if(action == 'up'):
new_index = index - self.cellsize
elif(action == 'down'):
new_index = index + self.cellsize
elif(action == 'left'):
new_index = index - 1
elif(action == 'right'):
new_index = index + 1
newState = PathFindingState([0]*49)
newState.cells = self.cells[:]
newState.cells[index] = 0
newState.cells[new_index] = 2
newState.currentLocation = new_index
newState.goalLocation = self.goalLocation
return newState
def __str__(self):
lines = []
dashLine = '-' * (self.cellsize*2 + 3)
lines.append(dashLine)
for n in range(self.cellsize):
newLine = '|'
for cell in self.cells[self.cellsize*n:self.cellsize*(n+1)]:
if cell == 0:
newLine += ' '
elif cell == 1:
newLine += 'X'
elif cell == 2:
newLine += 'S'
elif cell == 3:
newLine += 'G'
newLine += '|'
newLine = ' '.join(newLine)
lines.append(newLine)
lines.append(dashLine)
lines = '\n'.join(lines)
return lines
def __eq__(self, other):
return (self.cells == other.cells)
def __hash__(self):
return hash(str(self.cells))
### Part 2: define seacrh problem
class searchProblem:
def __init__(self, state):
self.state = state
def currentState(self):
return self.state
def nextStates(self, state):
next = []
for action in state.nextActions():
next.append((state.nextState(action), action, 1))
return next
def theEnd(self, state):
return state.goalState()
### Part 3: define seacrh method
def depthFirstSearch(problem):
fringeQueue = Queue.LifoQueue()
visited = set([])
path = ()
node = problem.currentState()
fringeQueue.put((node, path))
while (fringeQueue):
(node, path) = fringeQueue.get()
if problem.theEnd(node):
return path
break
if node not in visited:
successors = problem.nextStates(node)
visited.add(node)
else:
successors = []
for successor in successors:
if successor[0] not in visited:
fringeQueue.put(( successor[0], path+(successor[1],) ))
def breadthFirstSearch(problem):
fringeQueue = Queue.Queue()
visited = set([])
path = ()
node = problem.currentState()
fringeQueue.put((node, path))
while (fringeQueue):
(node, path) = fringeQueue.get()
if problem.theEnd(node):
return path
break
if node not in visited:
successors = problem.nextStates(node)
visited.add(node)
else:
successors = []
for successor in successors:
if successor[0] not in visited:
fringeQueue.put(( successor[0], path+(successor[1],) ))
def manDistance(state):
cx = state.currentLocation%7
cy = state.currentLocation//7
gx = state.goalLocation%7
gy = state.goalLocation//7
return ( abs(gx-cx) + abs(gy-cy) )
def greedySearch(problem):
fringeQueue = Queue.PriorityQueue()
visited = set([])
priority_number = 0
path = ()
node = problem.currentState()
fringeQueue.put(( priority_number, (node, path) ))
while (fringeQueue):
(priority_number, (node, path)) = fringeQueue.get()
if problem.theEnd(node):
return path
break
if node not in visited:
successors = problem.nextStates(node)
visited.add(node)
else:
successors = []
for successor in successors:
if successor[0] not in visited:
priority_number = manDistance(successor[0])
fringeQueue.put(( priority_number, ( successor[0], path+(successor[1],) ) ))
def aStarSearch(problem):
fringeQueue = Queue.PriorityQueue()
visited = set([])
priority_number = 0
path = ()
node = problem.currentState()
fringeQueue.put(( priority_number, (node, path) ))
while (fringeQueue):
(priority_number, (node, path)) = fringeQueue.get()
if problem.theEnd(node):
return path
break
if node not in visited:
successors = problem.nextStates(node)
visited.add(node)
else:
successors = []
for successor in successors:
if successor[0] not in visited:
priority_number = len(path) + manDistance(successor[0])
fringeQueue.put(( priority_number, ( successor[0], path+(successor[1],) ) ))
### Part 4: main program
if __name__ == '__main__':
numberList = [ 0, 0, 0, 0, 0, 0, 0, \
0, 0, 0, 0, 0, 0, 0, \
0, 2, 0, 0, 1, 0, 0, \
0, 0, 0, 0, 0, 0, 0, \
0, 1, 0, 0, 1, 0, 0, \
0, 0, 0, 0, 1, 3, 0, \
0, 0, 0, 0, 0, 0, 0 ]
state = PathFindingState(numberList)
problem = searchProblem(state)
path = depthFirstSearch(problem)
# path = breadthFirstSearch(problem)
# path = greedySearch(problem)
# path = aStarSearch(problem)
print('========================================')
print('Need %d moves to solve this puzzle: %s' % (len(path), str(path)))
print('========================================')
print(state)
i = 1
for action in path:
state = state.nextState(action)
print('move#%d: %s' % (i, action))
print(state)
i += 1