3

As far as I know, Breadth-First-Search [BFS] theory traditionally requires a Queue to process a given level of a graph (i.e: wiki seems to assume so).

But does BFS really actually require a Queue, rather than just any type of Collection?

  • A Queue is a Collection
  • A Set is also a Collection, for example

Wiki states that BFS...

"explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level."

What about that quote requires specifically a Queue? Why would BFS not work if implemented with any other type of Collection besides a Queue?

It seems to me that as long as any Collection is used to explore "all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level", by storing such neighbor nodes in that Collection and ensuring the entire Collection is emptied (or otherwise completely processed or explored) before moving on to the next depth level, then the level-ordering requirement of BFS is achieved?

I understand that a Queue would ensure a certain order (i.e: left-to-right) while processing/exploring within a given level; but is that ordering within a given level really necessary such that the algorithm still meet the requirements of BFS? Otherwise why is order within a given level actually necessary?

cellepo
  • 150
  • 6

1 Answers1

5

It doesn't literally have to be a queue. Anything that ensures that one level is completely explored before moving to the next one would suffice. However, the most natural way to do this is with a queue and any other implementation is going to be harder to describe and/or harder to implement than just "use a queue."

As evidence that it's harder to describe, note that your claim in the question that it suffices to ensure that the collection is empty before moving onto the next level is incorrect. Consider the following tree.

    1
   / \
  2   3
  .   .
  .   .
  .   .

We start searching at nodeĀ 1. We place its children 2 andĀ 3 in the collection. So the collection isn't empty but it's definitely time to move on to the next level.

OK, how do we fix this? Well, we could have two collections: one for the current level and one for the nodes that need to be expanded at the next level. Each time we process a node at the current level, we add its children to the "next level" collection. When the current level is all done, the "next level" collection becomes the "current level" collection, and we start a new, empty, "next level". OK, that works, but it's harder to describe than using a queue. On the other hand, if you want to claim that it's easier to prove that the two-collection version is correct, you'd have a point. Really, everything is a trade-off.

David Richerby
  • 82,470
  • 26
  • 145
  • 239