-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbf.js
More file actions
31 lines (25 loc) · 832 Bytes
/
Copy pathbf.js
File metadata and controls
31 lines (25 loc) · 832 Bytes
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
function findLowestCostPathBF(graph) {
const startNode = graph.nodes[graph.start]
const targetNode = graph.nodes[graph.target]
let _bestPath = null
_searchPathsBF(startNode, targetNode)
return _bestPath
function _searchPathsBF(node, target, visited = [], path = { cost: 0, nodes: [startNode.id] }) {
if (node.id === target.id) {
if (_bestPath === null)
_bestPath = path
if (_bestPath.cost > path.cost)
_bestPath = path
return
}
for (let outEdge of node.output
.filter(_e => !visited.some(v => v === _e.from))
) {
const _node = graph.nodes[outEdge.to]
_searchPathsBF(_node, target, visited.concat(node.id),
{ cost: path.cost + outEdge.weight, nodes: [...path.nodes, _node.id] }
)
}
}
}
module.exports = { findLowestCostPathBF }