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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With