Question
NOTE: This problem is a significantly more challenging version of Problem 81.
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is indicated in bold red 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 moving left, right, up, and down.
JavaScript
const fs = require("fs")
function parseMatrix(matrix) {
return matrix.toString().trim().split("\n").map((line) => {
return line.split(",").map((c) => parseInt(c))
})
}
function bfs(graph, root, target) {
function neighbors([x, y]) {
const candidates = [
- 1, y],
[x + 1, y],
[x , y - 1],
[x, y + 1]
[x
]return candidates.filter(([x, y]) => {
return x >= 0 && x < graph[0].length && y >= 0 && y < graph.length
})
}
function evaluate(path) {
return path.reduce((acc, [x, y]) => acc + graph[y][x], 0)
}
const start = [root]
const frontier = [[evaluate(start), start]]
const explored = new Set()
while (frontier.length > 0) {
let path = null
let min = Infinity
let index = -1
.forEach(([score, candidate], i) => {
frontierif (score < min) {
= score
min = candidate
path = i
index
}
}).splice(index, 1)
frontierconst node = path[path.length - 1]
.add(node.toString())
exploredif (node.toString() === target.toString()) {
return min
}neighbors(node).forEach((neighbor) => {
if (!explored.has(neighbor.toString())) {
const newPath = path.slice()
.push(neighbor)
newPath.push([evaluate(newPath), newPath])
frontier
}
})
}
}
const graph = parseMatrix(fs.readFileSync(__dirname + "/matrix.txt"))
console.log(bfs(graph, [0, 0], [graph[0].length - 1, graph.length - 1]))
$ time node --use-strict path-sum.js
real 0m0.666s
user 0m0.895s
sys 0m0.055s
Python
#!/usr/bin/env python2
import os
import heapq
def parse(matfile):
return [[int(n) for n in row.split(',')] for row in matfile]
def distance(a, b):
return sum(abs(a[i] - b[i]) for i in range(len(a)))
def astar(matrix, targets, sources):
def neighbors(position):
= position
(x, y) = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]
candidates return [(x, y) for (x, y) in candidates if x >= 0 and x < len(matrix)
and y >= 0 and y < len(matrix[0])]
def evaluate(path):
= sum(matrix[y][x] for (x, y) in path)
f = min(distance(path[-1], target) for target in targets)
h return f + h
= set(targets)
targets = set(sources)
frontier = set()
explored = []
frontier_queue for source in sources:
= [source]
path
heapq.heappush(frontier_queue, (evaluate(path), path))
while frontier:
= heapq.heappop(frontier_queue)
(_, path) -1])
frontier.remove(path[-1])
explored.add(path[if path[-1] in targets:
return path
for neighbor in neighbors(path[-1]):
if neighbor not in frontier | explored:
frontier.add(neighbor)= path + [neighbor]
new_path
heapq.heappush(frontier_queue, (evaluate(new_path), new_path))
def main():
with open(os.path.join(os.path.dirname(__file__), "matrix.txt")) as matfile:
= parse(matfile)
matrix = [(len(matrix) - 1, len(matrix[0]) - 1)]
targets = [(0, 0)]
sources print(sum(matrix[y][x] for (x, y) in astar(matrix, targets, sources)))
if __name__ == "__main__": main()
$ time python3 path-sum.py
real 0m1.971s
user 0m1.970s
sys 0m0.000s