-
Notifications
You must be signed in to change notification settings - Fork 0
/
algBreadthFirstSearchGraph.js
76 lines (70 loc) · 1.95 KB
/
algBreadthFirstSearchGraph.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Given a graph of nodes, find the shortest path.
The nodes can potentially be circular.
*/
const visitedNodeBefore = (visitedList, currentNode) =>
visitedList.find(visitedNode => visitedNode.value === currentNode.value);
const getDestinationNode = (currentNode, nodeDestination) =>
currentNode.nextNodes.find(({ node }) => node === nodeDestination);
const generateNewPath = (path, child) => ({
pathing: `${path.pathing}, ${child.node}`,
totalDistance: path.totalDistance + child.distance,
});
const breadthFirstSearchGraph = ({
graph,
currentNode,
nodeDestination,
visited = [],
path = { pathing: 'a', totalDistance: 0 },
}) => {
if (!currentNode) {
return breadthFirstSearchGraph({
graph,
currentNode: graph.a,
nodeDestination,
});
}
if (visitedNodeBefore(visited, currentNode)) return;
if (!currentNode.nextNodes) return;
const destinationNodeInChild = getDestinationNode(
currentNode,
nodeDestination
);
if (destinationNodeInChild) {
return generateNewPath(path, destinationNodeInChild);
}
const traversedChildren = currentNode.nextNodes.map(child =>
breadthFirstSearchGraph({
graph,
currentNode: graph[child.node],
nodeDestination,
visited: [...visited, currentNode],
paths: generateNewPath(path, child),
})
);
const validPaths = traversedChildren.filter(child => child);
return validPaths.length > 0
? validPaths.sort((a, b) => a.totalDistance > b.totalDistance)[0]
: 'no valid paths';
};
const graph = {
a: {
value: 'booya',
nextNodes: [{ node: 'b', distance: 3 }, { node: 'c', distance: 6 }],
},
b: {
value: 'booya1',
nextNodes: [{ node: 'c', distance: 3 }, { node: 'd', distance: 6 }],
},
c: {
value: 'booya2',
nextNodes: [{ node: 'd', distance: 1 }, { node: 'e', distance: 2 }],
},
d: {
value: 'booya3',
},
e: {
value: 'booya4',
},
};
breadthFirstSearchGraph({ graph, nodeDestination: 'd' });