0

I am trying to write some BFS algorithm in Java and read online that we should maintain something like an array prev where prev[i] = j indicates that the node we visited before i was node j.

So suppose I have such an array. How do I recover the original path? Is there any sample codes I can look at for this? I don't really get the explanation in the solution it seems to just gloss over the steps in 'getting back' to the source.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
AndW
  • 726
  • 6
  • 31
  • You just reversly follow the parent/prev pointers. So you loop back from the destination, always looking up the `prev` entries, until you reach the source again. Collect the nodes while doing so and you have your path. – Zabuzard Oct 26 '21 at 07:00

2 Answers2

1

My understanding is that you have a parent array populated after BFS. The parent array holds the parent id of the node, in other words, the node that was visited just before current node. Once you have the array you can print the path like so:

void printPath(int[] parent, int i) {
    if(parent[i] == -1) {//Root node does not have a parent 
         return;
    } else {
        printPath(parent, parent[i]);
        System.out.println(i);
    }
}

Note that this representation will work only if you label/identify the nodes in your graph using integers 0 ... |V|. Another common representation is a Map(or dictionary).

Map<Node, Node> parentTree
sushant
  • 1,101
  • 2
  • 9
  • 15
0

Breadth-First-Search will usually require a queue with a FIFO order.

Here is some sample code for you to work with:

class Node<T> {
    Node<T> left;
    Node<T> right;
    T data;
}

public static void Main(String[] args) {
   Node<String> root; // assume this is initialized with plenty of children
   
   Queue<Node<String>> bfs_queue(root);

   while(!bfs_queue.empty()) {
       Node target = bfs_queue.get();
       if(target == null) continue;
       
       // Do something with the data
       System.out.println(target.data)

       bfs_queue.push(target.left);
       bfs_queue.push(target.right);
   }
}

As you can see, we use a queue to give us the first item that went in, while for every item that we extract across the entire breadth of the current level, we continuously add the target node children to prepare the search for the next level.

(Side note the code above is pseudo Java code but close enough)

Moshe Rabaev
  • 1,892
  • 16
  • 31