Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import re, sys, itertools
- import hashlib
- import astar
- import resource
- from heapq import heappush, heappop
- import math
- import pprint
- def pathTo(node, cameFrom):
- path = [node]
- while node in cameFrom:
- node = cameFrom[node]
- path.append(node)
- return list(reversed(path))
- def search(start):
- counter = itertools.count()
- closed = set()
- queue = [(start.heuristic(), next(counter), start)]
- bestCostTo = {start: 0}
- cameFrom = {}
- while len(queue) > 0:
- _, _, node = heappop(queue)
- if node.isGoal():
- return bestCostTo[node], pathTo(node, cameFrom)
- closed.add(node)
- for edgeCost, nextNode in node.neighbors():
- if nextNode in closed:
- continue
- if nextNode.isFailure():
- continue
- nextCost = bestCostTo[node] + edgeCost
- if nextCost >= bestCostTo.get(nextNode, float('inf')):
- continue
- cameFrom[nextNode] = node
- bestCostTo[nextNode] = nextCost
- heappush(queue,
- (nextCost + nextNode.heuristic(), next(counter), nextNode))
- return "failure", tuple()
- resource.setrlimit(resource.RLIMIT_AS, (1024**3 - 1024, 1024**3))
- hashes = {}
- def ha(s):
- if s in hashes:
- return hashes[s]
- return hashlib.md5(bytes(s, encoding='ascii')).hexdigest()
- pw = "veumntbg"
- class Node:
- def __init__(self, x, y, path):
- self.x = x
- self.y = y
- self.path = path
- def isGoal(self):
- return self.x == 3 and self.y == 3
- def isFailure(self):
- return False
- def neighbors(self):
- h = ha(pw + self.path)
- for dx, dy, d, i in ((0,-1,"U",0), (0,1,"D",1),(-1, 0, "L",2) ,(1,0,"R",3)):
- if self.x + dx >= 0 and self.x + dx < 4 and self.y + dy >= 0 and self.y + dy < 4:
- if ord(h[i]) >= ord('b'):
- yield -1, Node(self.x + dx, self.y + dy, self.path + d)
- def heuristic(self):
- if self.isGoal():
- return 0
- return -10000
- #return 6 - self.x - self.y
- def __eq__(self, other):
- return isinstance(other, Node) and \
- self.x == other.x and self.y == other.y and self.path == other.path
- def __hash__(self):
- return hash((self.x, self.y, self.path))
- def __repr__(self):
- return str(self.x) + " " + str(self.y) + " " + str(self.path)
- c, path = astar.search(Node(0,0,""))
- print(-c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement