-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtilesSearch.py
More file actions
64 lines (58 loc) · 1.96 KB
/
tilesSearch.py
File metadata and controls
64 lines (58 loc) · 1.96 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
# tilesSearch.py
#
# Search for sequence of moves to bring a randomized tile puzzle
# into order
import sys, sarg, time
from tiles import TileGame
try:
import Queue as Q # python ver. < 3.0
except ImportError:
import queue as Q
def main() :
board = sys.argv[1]
ratio = sarg.Int("ratio",2)
timed = sarg.Int("time",0)
game = TileGame(board)
startTime = time.time()
path = search(game,board,ratio)
elapsed = time.time()-startTime
if timed : timeMsg = "Search took %s secs" % round(elapsed,4)
else : timeMsg = ""
print("tilesSearch.py: Moves=%s %s" % (len(path),timeMsg))
for entry in path : print(entry)
def search(game, board, ratio) :
closed = {}
queue = Q.PriorityQueue()
origCost = game.futureCost(board)*ratio
orig = (origCost,0,board,None) # (cost,nMoves,board,parent)
queue.put(orig)
closed[orig] = True
expanded = 0
solution = None
while queue and not solution :
parent = queue.get()
expanded += 1
(parCost, parMoves, parBoard, ancester) = parent
empty, moves = game.getMoves(parBoard)
for mov in moves :
childBoard = game.makeMove(parBoard,empty,mov)
if closed.get(childBoard) : continue
closed[childBoard] = True
childMoves = parMoves+1
childCost = game.futureCost(childBoard)*ratio + childMoves
child = (childCost,childMoves,childBoard,parent)
queue.put(child)
if childBoard == game.goal : solution = child
if solution :
print("%s entries expanded. Queue still has %s" % \
(expanded, queue.qsize()))
# find the path leading to this solution
path = []
while solution :
path.append(solution[0:3]) # drop the parent
solution = solution[3] # to grandparent
path.reverse()
return path
else :
return []
if __name__ == "__main__" : main()