I can't write the steps of bfs algorithm, please helps advice. I have tried everything for two days.
The function takes as an argument an object representing a non-binary tree (a node can have more than two children) and returns an array of nodes corresponding to a breadth-first traversal. Bypass is carried out from left to right (ascending index in the array).
Example graph:
A
/ \
B C
/ \ / \
D E F G
The same in the object:
const graph = {
A: ['B', 'C'],
B: ['D', 'E'],
C: ['F', 'G'],
D: [],
E: [],
F: [],
G: [],
};
Test cases: bfs(graph) // ['A', 'B', 'С', 'D', 'E', 'F', 'G']
I use this:
const bfs = (graph, start, end) => {
// create a queue
let queue = [];
start = Object.keys(graph)[0]
const visited = [start];
// add a starting vertex to it
queue.push(start)
// loops as long as there is at least 1 element in the queue
while (queue.length > 0) {
// get the current vertex from the queue
const node = queue.shift()
// check this vertex on the way further
if (!graph[node]) {
graph[node] = []
}
// if the array contains an endpoint in the graph at the current vertex - return
if (graph[node].includes(end)) {
return visited;
} else {
queue = [...queue, ...graph[node]]
}
}
}
]
But the problem is that in the found algorithm, I always need to immediately indicate the endpoint, how to find the shortest path and return to write down the steps, I cannot decide on my own.