-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path8.algoritm_dijkstra.js
More file actions
55 lines (47 loc) · 1.31 KB
/
8.algoritm_dijkstra.js
File metadata and controls
55 lines (47 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// поиск кратчайшего пути в взвешенном графе
const graph = {}
graph.a = {b: 2, c: 1}
graph.b = {f: 7}
graph.c = {d: 5, e: 2}
graph.d = {f: 2}
graph.e = {f: 1}
graph.f = {g: 1}
graph.g = {}
function shortPath(graph, start, end) {
const costs = {}
const processed = []
let neighbors = {}
Object.keys(graph).forEach(node => {
if (node !== start) {
let value = graph[start][node]
costs[node] = value || 100000
}
})
let node = findNodeLowestCost(costs, processed)
while (node) {
const cost = costs[node]
neighbors = graph[node]
Object.keys(neighbors).forEach(neighbor => {
let newCost = cost + neighbors[neighbor]
if (newCost < costs[neighbor]) {
costs[neighbor] = newCost
}
})
processed.push(node)
node = findNodeLowestCost(costs, processed)
}
return costs
}
function findNodeLowestCost(costs, processed) {
let lowestCost = 100000
let lowestNode;
Object.keys(costs).forEach(node => {
let cost = costs[node]
if (cost < lowestCost && !processed.includes(node)) {
lowestCost = cost
lowestNode = node
}
})
return lowestNode
}
console.log(shortPath(graph, 'a', 'g'));