Question

so I am trying to do a breadth first search on a list of nodes that I have but I'm not sure where to start? I have a pretty good understanding of what a breadth first search is but I have no idea how to implement it. My code is as follows:

 Scanner scanner = new Scanner(System.in);
Was it helpful?

Solution

Breadth first search is performed on a tree, graph, or similarly structured data. The idea of implementing breadth first search is to explore one layer of nodes and at the same time store references to nodes in the next layer, so that you can return to them, after you finish the current layer.

In order to accomplish this, you can use some kind of a queue. You start at the first node and put all the connected nodes into the back of a queue. Then pick the first node from the queue and repeat.

If you're doing this over a tree structure, that's all there's to it, if you're searching a graph, you need to make sure, that you don't revisit nodes, otherwise you might end up running in circles. Hope this clears up the topic a bit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top