I have solved the project euler problem 83 using uniform cost search. This solution takes about 0.6s to solve. I want to know if anyone can get the code to run relatively faster without changing the general outline of the program.
import bisect
f = open('matrix.txt')
matrix = [[int(i) for i in j.split(',')] for j in f]
def uniformCostSearch(startNode):
frontier = []
frontier.append(startNode)
closedSet = set()
while not len(frontier) == 0:
currentNode = frontier.pop(0)
if currentNode.x == 79 and currentNode.y == 79:
return currentNode.priority
else:
if not (currentNode.x, currentNode.y) in closedSet:
closedSet.add((currentNode.x, currentNode.y))
possibleMoves = currentNode.neighbors()
for move in possibleMoves:
if not (move.x, move.y) in closedSet:
try:
index = frontier.index(move)
if move.priority < frontier[index].priority:
frontier.pop(index)
bisect.insort_left(frontier, move)
except ValueError:
# move is not in frontier so just add it
bisect.insort_left(frontier, move)
return -1
class Node:
def __init__(self, x, y, priority=0):
self.x = x
self.y = y
self.priority = priority
def neighbors(self):
tmp = [Node(self.x + 1, self.y), Node(self.x, self.y + 1),
Node(self.x - 1, self.y), Node(self.x, self.y - 1),]
childNodes = []
for node in tmp:
if node.x >= 0 and node.y >= 0 and node.x <= 79 and node.y <= 79:
node.priority = self.priority + matrix[node.y][node.x]
childNodes.append(node)
return childNodes
def __eq__(self, node):
return self.x == node.x and self.y == node.y
def __ne__(self, node):
return not self.x == node.x and self.y == node.y
def __cmp__(self, node):
if self.priority < node.priority:
return -1
elif self.priority > node.priority:
return 1
else:
return 0