def translate2moves(tile_solution): """ This function takes a tile solution and convert it in single moves. """ memoized = {} moves = [] for node in tile_solution[1:]: if not node.action in memoized: p = TileProblem(node.action, node.action.getGoal()) end_node = depth_first_tree_search(p) assert end_node != None reloc_moves = end_node.path() reloc_moves.reverse() memoized[node.action] = reloc_moves displacement = (node.action.boardStart[0] - node.action.start[0], node.action.boardStart[1] - node.action.start[1]) moves.extend([mv.action.displace(displacement) for mv in memoized[node.action][1:]]) return moves
# Solve the nQueens problem by using depth-first search from time import time from datetime import timedelta from aima.search import depth_first_tree_search, NQueensProblem, Problem def secondsToStr(t): return str(timedelta(seconds=t)) def now(): return secondsToStr(time()) # 1. Set up the problem and set the starting time n = 30 print "\nStarting at at " + now()[12:20] print "problem with n =", n start = time() # 2. Solve the NQueens problem with depth-first search solution = depth_first_tree_search(NQueensProblem(n)) sol = str(solution) print "Solution: ", sol[5:len(sol) - 1] # 3. Print time elapsed end = time() elapsed = end - start print "\nElapsed time ", secondsToStr(elapsed)[0:15], "\n"