Project Euler problem 83 asks:
In the 5 by 5 matrix below,
131 673 234 103 18 201 96 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331
the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is
131 → 201 → 96 → 342 → 234 → 103 → 18 → 150 → 111 → 422 → 121 → 37 → 331
and is equal to 2297.
Find the minimal path sum, in
matrix.txt
(right click and 'Save Link/Target As...'), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.
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