Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the actual path found by BFS?

The problem I'm trying to solve concerns a tree of MRT system.

Each node can be connected to 4 points at most, which simplify thing by a lot. Here's my thought.

struct stop {
    int path, id;
    stop* a;
    stop* b;
    stop* c;
    stop* d;
};

I can write code to save all the information I need for BFS to search for all the points, but my main concern is that, even though BFS finds the point properly, how can I know its path?

BFS will search each level, and when one of it reaches my destination, it will jump out of the run loop, and then, I will get a visited queue and an unvisited queue, how am i supposed to tell the user what stops he needs to visit when the visited queue is filled with every nodes BFS has searched?

like image 795
Shane Hsu Avatar asked Mar 06 '12 19:03

Shane Hsu


People also ask

How do I find my BFS path?

Create a graph using the given nodes and a queue for storing the nodes to iterate through breadth-first search. Push v1 to the queue and start Breadth-first search till the queue is not empty. Iterate through all the connected nodes from the current node. Update the parent of new nodes.

How do you find the path on a graph?

Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as a source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false.

When would you use BFS to determine the shortest path?

Breadth first search is one of the basic and essential searching algorithms on graphs. As a result of how the algorithm works, the path found by breadth first search to any node is the shortest path to that node, i.e the path that contains the smallest number of edges in unweighted graphs.

Can BFS be used to find path?

Technically, Breadth-first search (BFS) by itself does not let you find the shortest path, simply because BFS is not looking for a shortest path: BFS describes a strategy for searching a graph, but it does not say that you must search for anything in particular.


1 Answers

To do so, you need to store a map:V->V (from vertices to vertices), which will map from each node v, the vertex u that "discovered" v.

You will populate this map during the iterations of BFS.

Later - you can reconstruct the path by simply going from the target node (in the map) up until you get back to the source, which will be your path (reversed, of course).

Note that this map can be implemented as an array if you enumerate the vertices.

like image 108
amit Avatar answered Nov 09 '22 01:11

amit