amejiarosario / dsa.js-data-structures-algorithms-javascript

🥞Data Structures and Algorithms explained and implemented in JavaScript + eBook

Home Page:https://books.adrianmejia.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Difficulty figuring out how to use BFS on the graph structure

plasmak opened this issue · comments

Hi
I find it not easy to understand how to use the bfs generator in practice.
Let say i have built a huge graph using the Graph class you have provided.
For a given node, I'd like to find out which are its immediate neighbors.
How would I use the BFS for that ?
Or should I just get the node entry and check its adjacents hashmap and export it to an array?
Thanks in advance

Nevermind, I have RTFM deeper in the repo and found examples in other function/data structures :)

Hi Aït-Kaci, glad to hear you find examples. Feel free to let me know if you have any other question

Thanks a lot. I'm trying to modify the BFS algorithm to just find the nodes that are directly connected to any given node: its neighbors. I'm not quite there but I have figured out how to use the BFS. If you have any tips on this, I'd appreciate it.
Actually the question of knowing if I should do a BFS or just look up the Adjacent nodes of the node remains open.

You don't need BFS to find immediate nodes, you can use getAdjacents:

Here's an example:

expect(n4.getAdjacents().map(getValues)).toEqual([1, 3]);

BFS is used to search. If you have a huge graph and you know that the node you are looking for is close to a certain point then you can use BFS is the right choice. However, if the graph is not too big and the value might be far from the initial point, then you can use DFS.

Here's a code example of how you can use BFS to search a node, check it out:
https://runkit.com/amejiarosario/dsa-js-graph-bfs

If you want to learn more about how to BFS, and how to apply in job interviews (without dsa.js nor generators). Check out this posts, it even goes through some real questions I got in 2 interviews: https://adrianmejia.com/how-to-solve-any-graph-2d-arrays-maze-interview-questions-in-javascript-dfs-vs-bfs/

Again: huge thanks for all the pointers. I had implmented it using getAdjacents but I worried that a BFS with distance tracking would be more efficient. Now I've got your answer so my questionning is over. Also, I bought the book to support your work ;)

You are welcome! and thanks for the support