Created
May 3, 2020 13:36
-
-
Save artzub/5c9bdbc0f746cf9dca5b37b2ace18d8b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
const calc = (src, dest, graph) => { | |
const length = graph.length; | |
const distance = new Array(length).fill(Infinity); | |
const parents = []; | |
const visited = []; | |
let l = length; | |
let node; | |
distance[src] = 0; | |
while(l--) { | |
node = -1; | |
distance.forEach((value, i) => { | |
if (!visited[i] && (node < 0 || value < distance[node])) { | |
node = i; | |
} | |
}); | |
if (distance[node] === Infinity) { | |
break; | |
} | |
visited[node] = true; | |
graph[node].forEach(to => { | |
const len = Math.pow(to - node, 2); | |
const dist = distance[node] + len; | |
if (dist < distance[to]) { | |
distance[to] = dist; | |
parents[to] = node; | |
} | |
}); | |
} | |
node = +dest; | |
const min = distance[node]; | |
const path = []; | |
while(node != src) { | |
path.unshift(node); | |
node = parents[node]; | |
} | |
path.unshift(+src); | |
return { min, path }; | |
}; | |
const run = () => { | |
const size = prompt('size', 10); | |
const graph = new Array(size); | |
const example = [[1,2,3],[4,6,8],[3,7,8],[7,8],[6],[7,8],[4,9],[4,6],[1],[1,4]]; | |
for(let i = 0; i < size; i++) { | |
graph[i] = prompt(`edges from ${i}`, example[i] && example[i].join('')).split('').map(n => +n); | |
} | |
console.log(JSON.stringify(graph)); | |
const src = prompt('from', 0); | |
const dest = prompt('to', 9); | |
const result = calc(src, dest, graph); | |
console.log(result); | |
} | |
run(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment