简体   繁体   中英

Path Between 2 nodes using BFS

I have written a function that calculates if a destination vertex is reachable from the source vertex using BFS. Now i need to keep track of the path that I am using to reach to the vertex. I guess it shall be a small tweak where we can add the node to my path arraylist. Someone please help me out.

public Boolean isReachable(Node destination) {
    ArrayList<Node> visited = new ArrayList<>();
    LinkedList<Node> queue = new LinkedList<>();
    ArrayList<Node> path = new ArrayList<>();
    queue.add(this);

    while (queue.size() != 0) {
        Node source = queue.poll();

        for (Node node : source.adjacentNodes) {
            if (node.equals(destination))
                return true;

            if (!visited.contains(node)) {
                visited.add(node);
                queue.add(node);
            }

        }
    }
    return false;
}

There are two parts to BFS that you're missing. BFS is used to find a path between nodes but it also tries to find the shortest path (but only of the nodes that it has searched) so there is typically a cost value involved. Since you only care if the nodes are connected then you don't need this cost value.

The second part that is missing is keeping track of the parent node that lead to the current node from the queue. See the pseudo-code written here: https://en.wikipedia.org/wiki/Breadth-first_search Note their use of n.parent and n.distance.

Keep track of the current node's parent reference in another data structure or add a pointer to the parent node inside of your Node objects. Then once the current node equals the destination node you can follow the parent node pointers backwards to the starting node. That will give you the full path from the finish node to the start node .

If you want the path from start to finish you'll need to iterate through the parent nodes and store a reference to them in a list or something and reverse the list when you're done.

So you got your bfs algorithm, but cannot retrieve the actual path. All you need to do is to search whether the same questions had already been answered before .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM