I want to do BFS on a 2D array, and each of the cell can be represented as pair<int,int>
. I use queue<pair<int,int>>
to keep track of cells at each level, but I find no clever way to keep track of the depth. (I don't want to define another struct to record the depth at each level)
How to keep track of depth in breadth first search?
Here is a solution in Java. Each level is ended with null
, and we increment the depth once we see null
.
I am wondering if there's a similar elegant solution in C++. For now, I can think of the following ways:
1) count the number of cells(push()
) at each level, and decrement the count after each pop()
. Once count == 0
, increase the depth.
2) use two queue
and replace the old one with the new one at the end of each level. Increase the depth at the end of each iteration.
3) maybe stores a pointer to pair<int,int>
in the queue and use NULL
to separate levels?