If you come here for a solution to the problem, you are in a wrong place.

Because **my code for this quiz wasn’t accepted yet** and the purpose of this post is to make a summary about what I have learnt about BFS from doing this exercise.

I will share my code at the end of this post and any ideas on where my code is wrong would be greatly appreciated.

##### When Should We Use BFS

When the target is to find the shortest path,BFS is a good choice.

If you do not have to find all the shortest paths, then you can stop whenever the first path is found.

Otherwise you would have to wait until all the nodes from current layer are processed.

##### How to Implement BFS

Use a queue to store the tree, and take advantage of the FIFO characteristic of queue to implement BFS.

##### Optimizations You May Want To Use With BFS

- Use adjacency matrix to store the relationships between nodes so you only has to do this calculation once.
- Save the length of the first path you found, whenever the depth of another path is larger than it, you can safely ignore that path.
- Save all the nodes of current layer and remove them when depth increasing to improve efficiency of further searches.

##### A Mistake You May Make When Using BFS

Possibility exists that you may include paths that are longer than the shortest ones in your result set so do a filter to get rid of them.

Luckily, you only need to take care of this when you are required to find all the shortest paths.

##### Lessons I Have Learnt about Javascript

The Right Way to Check the Existence of an Element Within an Array

I used`!array.findIndex(element !== target)`

to check if target is not in array , but this was wrong when target is the first element of array.

The right way is to use`array.findIndex(element !== target)===undefined`

.A Fast Way to Get the Last Element of an Array

`array.slice(-1)[0]`

.

Here comes the code, I have no idea which part is wrong…lol.

1 | function Queue(first) { |