Public
Edited
Dec 18, 2023
2 stars
Insert cell
Insert cell
Insert cell
show(tree01)
Insert cell
cost = [...input.replaceAll("\n", "")].map(Number)
Insert cell
W = Math.sqrt(cost.length)
Insert cell
Insert cell
import { shortest_tree } from "@fil/dijkstra"
Insert cell
Insert cell
makeGraph = (cost, min, max) => {
const sources = [];
const targets = [];
const costs = [];
for (let x = 0; x < W; ++x) {
for (let y = 0; y < W; ++y) {
for (let z = 0; z <= 1; ++z) {
for (let dir = -1; dir <= 1; dir += 2) {
let c = 0;
let x0 = x;
let y0 = y;
for (let i = 1; i <= max; ++i) {
if (z) {
y0 += dir;
if (y0 < 0 || y0 >= W) break;
} else {
x0 += dir;
if (x0 < 0 || x0 >= W) break;
}
c += cost[x0 + y0 * W];
if (i >= min) {
sources.push(((x + W * y) << 1) + z);
targets.push(((x0 + W * y0) << 1) + (1 - z));
costs.push(c);
}
}
}
}
}
}
return { sources, targets, costs };
}
Insert cell
graph01 = makeGraph(cost, 0, 3)
Insert cell
tree01 = shortest_tree({ graph: graph01, origins: [0, 1] })
Insert cell
answer01 = d3.min(tree01.cost.slice(-2))
Insert cell
Insert cell
tree02 = shortest_tree({ graph: makeGraph(cost, 4, 10), origins: [0, 1] })
Insert cell
answer02 = d3.min(tree02.cost.slice(-2))
Insert cell
show(tree02)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
tree03 = shortest_tree({ graph: makeGraph(cost, min, max), origins: [0, 1] })
Insert cell
Insert cell
function show(tree) {
let node = d3.minIndex(tree.cost.slice(-2)) + ((W ** 2 - 1) << 1);
const path = [node];
while ((node = tree.predecessor[node]) > -1) path.push(node);
return Plot.plot({
inset: 2,
grid: true,
x: { domain: [0, W - 1] },
y: { domain: [W - 1, 0] },
color: { scheme: "blues" },
aspectRatio: 1,
marks: [
Plot.raster(cost, {
x: (_, i) => i % W,
y: (_, i) => Math.floor(i / W),
fill: Plot.identity,
interpolate: "nearest"
}),
Plot.frame(),
Plot.line(path, {
x: (i) => (i >> 1) % W,
y: (i) => Math.floor((i >> 1) / W),
stroke: "orange",
z: null
})
]
});
}
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more