public int bfs(int maxDepth){
int src = 2;
int dest = 2;
int i;
int depth = 0;
int countPaths = 0;
int element;
queue.add(src);
while(!queue.isEmpty() && depth <= maxDepth)
{
element = queue.remove();
i = 0;
while(i < 5)
{
if(arr[element][i] > 0)
{
queue.add(i);
if(i == dest)
countPaths++;
}
i++;
}
}
queue.clear();
return countPaths;
}
Hello!! Given a source and a destination, I need to find a path. My BFS algorithm is working fine as far as traversing the graph goes. My problem is getting it to stop when I want it to. I took out where I was incrementing depth so I don't look like a complete idiot. I hope someone can help. Essentially I want to know how I can keep track of the current depth. Thank you!
Example:
Find the # of paths from C to C with a maximum number of 3 stops. The answer is two paths:
C -> D -> C (2 stops)
C -> E -> B -> C (3 stops)
Example 2: Find the # of paths from A to C with a maximum number of 3 stops. The answer is three paths.
A -> B -> C (2 stops)
A -> D -> C (2 stops)
A -> E -> B -> C -> (3 stops)
depth
to measure how deep you are going. Have you considered using another queue to keep track of depth? let's call itdepth_queue
. Each element indepth_queue
is the depth of an element inqueue
. The way I see it, there are two strategies to detect when to terminate: (1) the head ofdepth_queue
is more thanmaxDepth
(not sure if this is the case, you need to think on it) (2) this is more assuring: go through the entiredepth_queue
if every element is more thanmaxDepth
, then you can terminate – Hershelhershell