How does a Breadth-First Search work when looking for Shortest Path?

前端 未结 8 1444
太阳男子
太阳男子 2020-11-30 16:52

I\'ve done some research, and I seem to be missing one small part of this algorithm. I understand how a Breadth-First Search works, but I don\'t understand how exactly it wi

相关标签:
8条回答
  • 2020-11-30 17:17

    A good explanation of how BFS computes shortest paths, accompanied by the most efficient simple BFS algorithm of which I'm aware and also by working code, is provided in the following peer-reviewed paper:

    https://queue.acm.org/detail.cfm?id=3424304

    The paper explains how BFS computes a shortest-paths tree represented by per-vertex parent pointers, and how to recover a particular shortest path between any two vertices from the parent pointers. The explanation of BFS takes three forms: prose, pseudocode, and a working C program.

    The paper also describes "Efficient BFS" (E-BFS), a simple variant of classic textbook BFS that improves its efficiency. In the asymptotic analysis, running time improves from Theta(V+E) to Omega(V). In words: classic BFS always runs in time proportional to the number of vertices plus the number of edges, whereas E-BFS sometimes runs in time proportional to the number of vertices alone, which can be much smaller. In practice E-BFS can be much faster, depending on the input graph. E-BFS sometimes offers no advantage over classic BFS but it's never much slower.

    Remarkably, despites its simplicity E-BFS appears not to be widely known.

    0 讨论(0)
  • 2020-11-30 17:21

    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.

    Dijkstra's algorithm adapts BFS to let you find single-source shortest paths.

    In order to retrieve the shortest path from the origin to a node, you need to maintain two items for each node in the graph: its current shortest distance, and the preceding node in the shortest path. Initially all distances are set to infinity, and all predecessors are set to empty. In your example, you set A's distance to zero, and then proceed with the BFS. On each step you check if you can improve the distance of a descendant, i.e. the distance from the origin to the predecessor plus the length of the edge that you are exploring is less than the current best distance for the node in question. If you can improve the distance, set the new shortest path, and remember the predecessor through which that path has been acquired. When the BFS queue is empty, pick a node (in your example, it's E) and traverse its predecessors back to the origin. This would give you the shortest path.

    If this sounds a bit confusing, wikipedia has a nice pseudocode section on the topic.

    0 讨论(0)
提交回复
热议问题