简体   繁体   中英

Find a path with BFS in a graph

I want to find a path between two nodes in a graph with a bfs. I wrote a function that visit all nodes in the correct order (not sure if it works, but it seems right to me) but I need to store the the path (with a list of all edges that makes the path) and I don't know how to do it :\\

Can someone help me ? Thanks in advance :)

You create an array p of parents. So if p[u] = v there is an edge from v to u in the path from the source to u . Where the parent of the source vertex is null .

So when we are in the current vertex v , before inserting its adjacent vertex u in the queue, we make p[w] = v . When you find the destination vertex you go backward in the array p. Starting from the destination vertex w , p[w] is the parent of w and p[p[w]] is the parent of the parent of w and so on.

This can be one of the approaches.

In this approach you keep a queue of lists in which you get the list and get the first node from that list.

find the adj() of that node and for each node not visited add a new path+[node] in the queue , also if the destination is reached return that path+[node] .

step 1 : create a queue of to hold the paths.
step 2 : add the source as  [ source ] in the queue
step 3 : while the queue is not empty get one path from it
         (as this works for both bfs and dfs thats why "get" not "dequeue" or "pop")

step 4: get the last node of that path (list)
step 5: get the adj of that node and for each not explored create a new path i.e oldpath +[adj node]

step 6:if the adj node is what u want then return the path else add the path to the queue

I hope this was helpful.

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