Skip to content

Commit a90c6e6

Browse files
author
minhaz.raufoon
committed
bfs done
1 parent 8447046 commit a90c6e6

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
function BFSFindShortestPath(graph, srcNode, dstNode) {
2+
var isPushed = Object.create(null),
3+
bfsQueue,
4+
currentNode,
5+
childNode,
6+
parentNodeOf = Object.create(null),
7+
shortestPath;
8+
9+
bfsQueue = [srcNode];
10+
parentNodeOf[srcNode] = null;
11+
isPushed[srcNode] = true;
12+
13+
while (bfsQueue.length > 0) {
14+
currentNode = bfsQueue.shift();
15+
if (currentNode === dstNode) break;
16+
17+
for (var i = 0; i < graph[currentNode].length; i++) {
18+
childNode = graph[currentNode][i];
19+
if (isPushed[childNode]) continue;
20+
21+
parentNodeOf[childNode] = currentNode;
22+
bfsQueue.push(childNode);
23+
isPushed[childNode] = true;
24+
}
25+
}
26+
27+
if (!isPushed[dstNode]) {
28+
return {
29+
distance: Infinity,
30+
shortestPath: []
31+
}
32+
}
33+
34+
shortestPath = [dstNode];
35+
currentNode = dstNode;
36+
37+
while (parentNodeOf[currentNode]) {
38+
currentNode = parentNodeOf[currentNode];
39+
shortestPath.unshift(currentNode);
40+
}
41+
42+
return {
43+
distance: shortestPath.length - 1,
44+
shortestPath: shortestPath
45+
}
46+
}
47+
48+
49+
/* TESTING */
50+
var graph = {
51+
1: [2, 3],
52+
2: [1, 3, 4, 5],
53+
3: [1, 2, 4],
54+
4: [2, 3, 5],
55+
5: [2, 4],
56+
}
57+
var srcNode = 1, destNode = 5;
58+
59+
console.log(BFSFindShortestPath(graph, srcNode, destNode));

0 commit comments

Comments
 (0)