I am working on BFS algorithms and I'm having a hard time figuring out how to keep track of the shortest path.
Below the code I've used :
const graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13],
};
function bfs(graph, start, end) {
let queue = [...graph[start]];
let path = [start];
let searched = [];
while (queue.length > 0) {
let curVert = queue.shift();
if (curVert === end) {
return path;
} else if (searched.indexOf(curVert) === -1 && graph[curVert]) {
queue = [...queue, ...graph[curVert]];
searched.push(curVert);
path.push(curVert);
}
}
}
console.log(bfs(graph, 1, 13));
what I would to get in return of the function call is the shortest path. In this case [1, 4, 7, 11, 13].