Question
NOTE: This problem is a more challenging version of Problem 81.
The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994.
|
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 left column to the right column.
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, sources, targets) {
function neighbors([x, y]) {
const candidates = [
+ 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 frontier = []
.forEach((source) => {
sourcesconst start = [source]
.push([evaluate(start), start])
frontier
})const destinations = new Set()
.forEach((target) => {
targets.add(target.toString())
destinations
})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 (destinations.has(node.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"))
const sources = []
const targets = []
for (let i = 0; i < graph.length; i++) {
.push([0, i])
sources.push([graph[0].length - 1, i])
targets
}console.log(bfs(graph, sources, targets))
$ time node --use-strict path-sum.js
real 0m0.951s
user 0m1.133s
sys 0m0.047s
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, y - 1), (x, y + 1), (x + 1, y)]
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(row) - 1, y) for y, row in enumerate(matrix)]
targets = [(0, y) for y, row in enumerate(matrix)]
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.978s
user 0m1.970s
sys 0m0.008s