function solve (graph, s) {
const solutions = {}
solutions[s] = []
solutions[s].dist = 0
while (true) {
let p = null
let neighbor = null
let dist = Infinity
for (const n in solutions) {
if (!solutions[n]) { continue }
const ndist = solutions[n].dist
const adj = graph[n]
for (const a in adj) {
if (solutions[a]) { continue }
const d = adj[a] + ndist
if (d < dist) {
p = solutions[n]
neighbor = a
dist = d
}
}
}
if (dist === Infinity) {
break
}
solutions[neighbor] = p.concat(neighbor)
solutions[neighbor].dist = dist
}
return solutions
}
const graph = {}
const layout = {
R: ['2'],
2: ['3', '4'],
3: ['4', '6', '13'],
4: ['5', '8'],
5: ['7', '11'],
6: ['13', '15'],
7: ['10'],
8: ['11', '13'],
9: ['14'],
10: [],
11: ['12'],
12: [],
13: ['14'],
14: [],
15: []
}
for (const id in layout) {
if (!graph[id]) { graph[id] = {} }
layout[id].forEach(function (aid) {
graph[id][aid] = 1
if (!graph[aid]) { graph[aid] = {} }
graph[aid][id] = 1
})
}
const start = '10'
const solutions = solve(graph, start)
console.log("From '" + start + "' to")
for (const s in solutions) {
if (!solutions[s]) continue
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
}